堆优化的LRU换页算法

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值