1. 程式人生 > >先進先出頁面置換演算法(FIFO)

先進先出頁面置換演算法(FIFO)

演算法規則:

顧名思義,最早進來的元素,若發生缺頁要最先出去。

 

code:

#include <iostream>
#include <cstdlib>
#include <vector>
#include <cstdio>

#define pause system("pause")

using namespace std;

const int maxn = 1005;

int a[maxn];
int b[maxn];
int top;

void init(int m)
{
	top = 0;
	for (int i = 0; i < m; i++) b[i] = -1;
}

int insert(int val, int m)
{
	int flag = 1;

	for (int i = 0; i < m; i++)
	{
		if (b[i] == val)
		{
			flag = 0;
			break;
		}

		if (b[i] == -1)
		{
			flag = 0;
			b[i] = val;
			break;
		}
	}

	if (flag)
	{
		b[top] = val;
		top = (top + 1) % m;
	}

	for (int i = 0; i < m; i++) cout << b[i] << " ";
	cout << endl;

	return flag;
}

int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) cin >> a[i];

	int m;
	cin >> m;
	init(m);

	int cnt = 0;
	for (int i = 0; i < n; i++)
	{
		cnt += insert(a[i], m);
	}
	cout << cnt << endl;
	return 0;
}



/*

20
7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
3

*/

 

Input and Output