HDOJ-2835(最佳置換算法)

題目:http://acm.hdu.edu.cn/showproblem.php?pid=2835

如果數據以後都再也不會使用,則將其換出必然是最優的,但如果緩存中的數據以後都還會使用,那到底換出哪一個好呢?直觀上想,感覺換出最遠下次使用的數據更好,但如何證明其是最佳的,不會呢。。。


#include <cstdio>
#include <queue>
#include <set>
using namespace std;
#define MAX_B	100005
#define MAX_N	100005

int C, N;
int B, a[MAX_B];
queue<int> q[MAX_N];
struct Compare{
	bool operator()(int x, int y)const{
		//the rule when x should be in front of y
		return q[x].front() > q[y].front();
	}
};
set<int, Compare> cache;

bool input()
{
	if(scanf("%d%d%d", &C, &N, &B) != 3) return false;
	for(int i = 0; i < N; ++i){
		while(!q[i].empty()) q[i].pop();
	}
	for(int i = 0; i < B; ++i){
		scanf("%d", a+i);
		q[a[i]].push(i);
	}
	for(int i = 0; i < N; ++i) q[i].push(B);
	return true;
}

void run()
{
	cache.clear();

	int i = 0, tot = 0;
	set<int, Compare>::iterator iter;
	for(; i < B; ++i){
		iter = cache.find(a[i]);
		if(iter != cache.end()){
			//erase and insert, as the key will be altered
			cache.erase(iter);
			q[a[i]].pop();
			cache.insert(a[i]);
		}
		else{
			if(cache.size() >= C){
				//choose object with furthest next time to use
				cache.erase(*cache.begin());
			}
			q[a[i]].pop();
			cache.insert(a[i]);
			++tot;
		}
	}
	printf("%d\n", tot);
}

int main()
{
	while(input()) run();
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章