LRU management (模拟, stl)

15 篇文章 0 订阅
8 篇文章 0 订阅

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值