hdu 2835 Operating system (模拟)

题意:模拟OPT(最优页面置换算法),就是贪心。当需要换出页面的时候,选择cache中下一次访问时间最晚的页面换掉。

可以使用 set<int> 存储在cache中的页面,对每一个页号维护一个访问时间队列。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<map>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
#include<set>
#include<list>
using namespace std;

const int maxn = 100000;
const int inf = 0x7fffffff;
int C, N ,B;
int cnt[maxn+5];

typedef list<int> Array;

Array sd[maxn+5];

class CMP {
public:
    bool operator () (int lhs, int rhs) const {
        Array& v1 = sd[lhs];
        Array& v2 = sd[rhs];
        return v1.front() > v2.front();
    }
};


int main() {
   // freopen("input.in", "r", stdin);
    while (cin >> C >> N >> B) {
        for (int i=0;i<=N;++i) sd[i].clear();
        vector<int> seq;
        set<int, CMP> m;
        for (int i=0;i<B;++i) {
            int tmp;
            cin >> tmp;
            sd[tmp].push_back(i);
            seq.push_back(tmp);
        }
        for (int i=0;i<N;++i) sd[i].push_back(inf);
        //for (int i=0;i<B;++i) cout << seq[i] << ' ';cout << endl;
        int ans = 0;
        for (int i=0;i<B;++i) {
#if 0
            cout << "set: ";
            for (set<int>::iterator it=m.begin();it!=m.end();++it) {
                cout << *it <<"(" << (sd[*it].front()) << ")" << ' ';
            }
            cout << endl;
#endif
            int k = seq[i];
            if (m.count(k)) {
                m.erase(m.find(k));
                sd[k].pop_front();
                m.insert(k);
            }
            else {
                ++ans;
                sd[k].pop_front();
                if (m.size() >= C) {
                    int tmp = *(m.begin());
                    m.erase(m.begin());
                    //cout << "hi: " << tmp << endl;
                }
                m.insert(k);
            }
        }
        cout << ans << endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值