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