#1086 : Browser Caching
http://hihocoder.com/problemset/problem/1086
题目意思很清楚,有一个M大小的Cache,和N次查询,需要判断每次查询是在从Cache中读出还是从Internet下载。
用一个小根堆来维护cache里每个元素的timestamp。
#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#include <map>
using namespace std;
map<int,int> cache; // name_id, timestamp
map<string,int> names; // name, name_id
map<int,int> name_heap; // name_id, heap_id
int N,M;
int get_id(string name) {
static int cnt = 1;
map<string,int>::iterator it = names.find(name);
if(it == names.end()) {
names[name] = cnt++;
}
return names[name];
}
const int MAXSIZE = 20000 + 10;
int heap[MAXSIZE]; // heap_id, timestamp (small is top)
int heap_name[MAXSIZE]; // heap_id, name_id
int heap_idx = 0;
void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}
void build_down(int root) {
int j = root * 2;
if(j + 1 < heap_idx && heap[j] > heap[j+1]) j += 1;
if(j < heap_idx && heap[root] > heap[j]) {
swap(heap[root],heap[j]);
swap(heap_name[root],heap_name[j]);
name_heap[heap_name[root]] = root;
name_heap[heap_name[j]] = j;
build_down(j);
}
}
bool query(int url_id) {
static int timestamp = 1;
map<int,int>::iterator it = cache.find(url_id);
if(it != cache.end()) {
it->second = timestamp;
int heap_id = name_heap[url_id];
heap[heap_id] = timestamp;
build_down(heap_id);
timestamp++;
return false;
}
else {
if(cache.size() < M) {
cache[url_id] = timestamp;
heap[heap_idx] = timestamp;
heap_name[heap_idx] = url_id;
name_heap[url_id] = heap_idx;
heap_idx++;
}else {
int heap_top_id = heap_name[0];
it = cache.find(heap_top_id);
cache.erase(it);
cache[url_id] = timestamp;
heap_name[0] = url_id;
heap[0] = timestamp;
build_down(0);
}
timestamp++;
return true;
}
}
int main(int argc, char* argv[]) {
while(scanf("%d%d",&N,&M)!=EOF) {
string url;
cache.clear();
for(int i=0; i<N; i++) {
cin >> url;
int url_id = get_id(url);
bool flag = query(url_id);
if(flag) printf("Internet\n");
else printf("Cache\n");
}
}
return 0;
}