OS実験課---ページ置換アルゴリズムOptimalとLRU


最適ページ置換アルゴリズムOptimal,(後続で出現する最小回数の置換)
最小使用アルゴリズムLRU
データ:
1 2 3 4 2 1 5 6 2 1 2 3 7 6 3 2 1 2 3 6


コード:
#include <cstdio>

#include <cstring>

#include <iostream>

#include <algorithm>

using namespace std;



const int PAGE_MAX_NUM = 4;

const int LEN_MAX = 100;



void Print(const int num, const int *p, const int len){

	printf("%d :%d",num,p[0]);

	for(int i = 1; i < len; i++){

		printf(" %d",p[i]);	

	}

	printf("
"); } void LRU(const int *list, const int len){ int i,lack; int hash[PAGE_MAX_NUM+1]; int time[PAGE_MAX_NUM+1]; for(i = 0; i< PAGE_MAX_NUM; i++){ hash[i] = 0; time[i] = 0;} lack = 0; hash[0] = list[0]; time[0] = 1; Print(1,hash,4); for(i = 1;i < len; i++){ for(int j = 0; j< 4; j++){ if(hash[j] == list[i]){ time[j] = i; Print(i+1,hash,4); break; } } if(j == 4) { lack ++; int min = 0; for(int j = 1;j < 4; j++){ if(time[j] < time[min]){ min = j; } } time[min] = i; hash[min] = list[i]; Print(i+1,hash,4); } } printf(" %d
",lack); } void Optimal(const int *list, const int len){ int i,lack; int hash[PAGE_MAX_NUM+1]; int time[LEN_MAX+1]; for(i = 0; i< PAGE_MAX_NUM; i++){ hash[i] = 0; } for(i = 0; i< LEN_MAX; i++){ time[i] = 0; } for(i = 0; i< len; i++){ time[list[i]] ++; } lack = 0; hash[0] = list[0]; time[list[0]]--; Print(1,hash,4); for(i = 1; i < len; i++){ for(int j = 0; j< 4; j++){ if(hash[j] == list[i]){ Print(i+1,hash,4); time[list[i]]--; break; } } if(j == 4){ lack ++; int min = 0; for(int j = 1;j < 4; j++){ if(time[hash[j]] < time[hash[min]]) min = j; } hash[min] = list[i]; time[list[i]]--; Print(i+1,hash,4); } } printf(" %d
",lack); } int main() { int list[100]; int a,len,flag; char c; len = 0; cout<<" , "<<endl; while( scanf("%d%c", &a, &c) ){ if( c == '
' ){
              list[len++] = a; printf( " Optimal <0>
LRU <1>
" ); scanf("%d", &flag); if(flag == 0){ Optimal(list, len); } else if(flag == 1){ LRU(list, len); } len = 0; }else{ list[len++] = a; } } return 0; }