7-2 Least Recently Used Cache

Least Recently Used Cache

(25分)

Least Recently Used (LRU) cache scheme is to remove the least recently used frame (the one hasn't been used for the longest amount of time) when the cache is full and a new page is referenced which is not there in cache.

Your job is to implement this LRU cache scheme.

Input Specification:

Each input file contains one test case. For each case, the first line gives 2 positive integers N (≤104) and M (≤105) which are the size of the cache and the number of referenced page ID's. Then M referenced page ID's are given in the next line. A page ID is a number in the range [1,2×104]. All the numbers in a line are separated by a space.

Output Specification:

For each test case, output in a line the page ID's in the order of their being removed from the cache. All the numbers in a line must be separated by 1 space, and there must be no extra space at the beginning or the end of the line.

It is guaranteed that at least one page will be removed.

When pages with ID's 1, 2, and 3 comes in order, they are all stored in the cache and page 1 is now the LRU frame.

When page 1 is accessed, page 2 then becomes the LRU frame.

Page 4 can still be stored in the cache, and now the cache is full. When page 5 is to be cached, page 2 will be removed and page 3 becomes the LRU frame.

When the next page 2 comes in, page 3 is removed and page 1 becomes the LRU frame.

Then page 1 is accessed, so page 4 becomes the LRU frame.

When page 5 is accessed, the LRU frame is not changed. Then page 6 comes in and page 4 is removed. The LRU frame is now page 2.

Finally page 2 is removed when page 3 comes in.

Sample Input:

4 11
1 2 3 1 4 5 2 1 5 6 3

Sample Output:

2 3 4 2

#include<iostream>
#include<queue>
using namespace std;
const int N = 10010,M = 100010,NUM = 20010;
int num[NUM],c;
int main(){
    int n,m;
    scanf("%d %d",&n,&m);
    queue<int> q;
    vector<int> res;
    while(m--){
        int x;cin>>x;
        if(c<n){
            if(num[x]==0) c++;
        }else{
            if(num[x]==0){
                while(num[q.front()]!=1){
                    num[q.front()]--;
                    q.pop();
                }
                num[q.front()]--;
                res.push_back(q.front());
                q.pop();
            }
        }
        q.push(x);
        num[x]++;
    }
    cout<<res[0];
    for(int i = 1;i<res.size();i++)cout<<" "<<res[i];
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值