ZYB has finished his computer course recently. He is very interested in the LRU algorithm for cache management.
To simplify the problem, assume that a block contains a name (which is a string) and a set of data (which is a number). ZYB wants to implement the LRU algorithm with an array.
His array can hold at most elements at any time. In the beginning, the array is empty. In each operation, the CPU may access a block
. ZYB will search for it in his array by brute force. If this block is present in his array (which means he can find a block with the same name), he takes it out of the array and puts it back at the end of the array. Otherwise, he simply adds it to the end of the array. If at any time, the size of the array exceeds the capacity, he will remove the first block in his array (the block at the front of the array).
Seems boring? Well, sometimes ZYB may ask the data of a block in, before or after a certain block. Could you help him to write a program to achieve his goal?
按照题意模拟就行了, 使用map, list。map映射list的迭代器。
STL巨好用。
/*
模拟 STL
*/
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
struct node{
string name;
int val;
};
unordered_map<string, list<node>::iterator>mp;
list<node>ls;
int n, m;
void fun(int op, string name, int val)
{
if (!op)
{
if (mp.find(name) == mp.end())
{
ls.push_back({ name, val });
mp[name] = --ls.end();
if (ls.size() > m)
{
mp.erase(ls.front().name);
ls.pop_front();
}
printf("%d\n", val);
}
else
{
auto i = mp[name];
printf("%d\n", i->val);
int num = i->val;
ls.erase(i);
ls.push_back({ name, num });
mp.erase(name);
mp[name] = --ls.end();
}
}
else
{
if (mp.find(name) == mp.end())
puts("Invalid");
else
{
auto i = mp[name];
if (val == 1)
{
if (i == --ls.end())
puts("Invalid");
else
printf("%d\n", next(i)->val);
}
else
if (val == -1)
{
if (i == ls.begin())
puts("Invalid");
else
printf("%d\n", prev(i)->val);
}
else
printf("%d\n", i->val);
}
}
}
int main(){
//freopen("D:/input.txt", "r", stdin);
int t;
cin >> t;
while (t--)
{
mp.clear();
ls.clear();
cin >> n >> m;
int op;
char name[11];
int val;
for (int i = 1; i <= n; i++)
{
scanf("%d", &op);
scanf("%s", name);
scanf("%d", &val);
string s = name;
fun(op, s, val);
}
}
return 0;
}