LRU management
解题思路
用map索引对应地址,用双向链表维护序列。
代码如下
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
inline int read(){
int res = 0, w = 0; char ch = 0;
while(!isdigit(ch)){
w |= ch == '-', ch = getchar();
}
while(isdigit(ch)){
res = (res << 3) + (res << 1) + (ch ^ 48);
ch = getchar();
}
return w ? -res : res;
}
const int N = 500005;
int l[N], r[N];
int data[N], cnt, tail, sum, front;
ll u[N];
map<ll, int> mp;
int main()
{
int t;
t = read();
while(t --){
int q, m;
scanf("%d%d%*c", &q, &m);
front = sum = tail = cnt = 0;
for(int i = 0; i <= q + 1; i ++)
u[i] = l[i] = r[i] = data[i] = 0;
for(int i = 1; i <= q; i ++){
int opt;
scanf("%d%*c", &opt);
ll s = 1;
char ch;
while((ch = getchar()) != ' ')
s = s * 10 + ch - '0';
int v;
scanf("%d", &v);
if(opt == 0){
if(mp.find(s) == mp.end()){
data[++cnt] = v;
u[cnt] = s;
mp[s] = cnt;
r[tail] = cnt;
l[cnt] = tail;
r[cnt] = 0;
tail = cnt;
printf("%d
", v);
if(sum == 0)
front = cnt;
++ sum;
}
else {
int k = mp[s];
printf("%d
", data[k]);
if(sum > 1){
if(k == front)
front = r[k];
if(k != tail){
r[l[k]] = r[k];
l[r[k]] = l[k];
r[tail] = k;
l[k] = tail;
r[k] = 0;
tail = k;
}
}
}
if(sum > m){
-- sum;
mp.erase(u[front]);
front = r[front];
l[front] = 0;
}
}
else {
if(mp.find(s) == mp.end()){
puts("Invalid");
continue;
}
int k = mp[s];
if(v == -1){
if(l[k])
printf("%d
", data[l[k]]);
else
puts("Invalid");
}
else if(v == 0){
printf("%d
", data[k]);
}
else {
if(r[k])
printf("%d
", data[r[k]]);
else
puts("Invalid");
}
}
}
mp.clear();
}
return 0;
}