您的位置:首页 > 其它

百度 页面调度算法

2016-06-14 16:49 323 查看
在计算机中,页式虚拟存储器实现的一个难点是设计页面调度(置换)算法。其中一种实现方式是FIFO算法。

FIFO算法根据页面进入内存的时间先后选择淘汰页面,先进入内存的页面先淘汰,后进入内存的后淘汰。

假设Cache的大小为2,有5个页面请求,分别为 2 1 2 3 1,则Cache的状态转换为:(2)->(2,1)->(2,1)->(1,3)->(1,3),其中第1,2,4次缺页,总缺页次数为3。

现在给出Cache的大小n和m个页面请求,请算出缺页数。

输入描述:

输入包含多组测试数据。

对于每组测试数据,第一行两个整数n,m。

然后有m个整数,代表请求页编号。

保证:

2<=n<=20,1<=m<=100,1<=页编号<=200.

输出描述:

对于每组数据,输出一个整数,代表缺页数

输入例子:

2 5

2 1 2 3 1

输出例子:

3

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
int n = scan.nextInt();
int m = scan.nextInt();
int[] pages = new int[m];
for (int i = 0; i < m; i++) {
pages[i] = scan.nextInt();
}
System.out.println(solve(n, m, pages));
}
scan.close();
}

private static int solve(int n, int m, int[] pages) {
//数组模拟cache
int[] cache = new int[101];
int count = 0;
int start = 0;//cache填满之后,FIFO.记录cache第一个页下标.
int end = 0;
int i;
//cache填满之前缺页
for (i = 0; i < m; i++) {
if (!check(cache, start,end, pages[i])) {
++end;
if (end > n) {
--end;
break;
}
cache[end - 1] = pages[i];
++count;
}
}
//cache填满之后,采用FIFO算法,缺页start+1,end+1.
for (; i < m; ++i) {
if (!check(cache, start,end, pages[i])) {
++count;
++start;
++end;
cache[end - 1] = pages[i];
}
}
return count;
}

private static boolean check(int[] cache, int start,int end, int x) {
for (int i = start; i < end; ++i) {
if (cache[i] == x) {
return true;
}
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  百度