页面替换算法

4种常见的

1、最佳置换算法(OPT)(理想置换算法)

2、先进先出置换算法(FIFO)

3、最近最久未使用(LRU)算法

4、时钟(CLOCK)置换算法

此方法是3的改进版,以下是思路的代码实现:
n代表任务数量,cnt代表物理分配内存数

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int x,n,m,k = 1,ans;
int h[10001],vis[10001];
bool cnt[10001];

void solve()
{
	cin >> n >> m;
	for(int i = 1;i <= m;i ++)
	{
		cin >> x;
		h[i] = x,cnt[x] = 1;
	}
	ans = m;
	for(int i = m + 1; i <= n;i ++)
	{
		cin >> x;
		if(cnt[x]) continue;
		ans ++;
		if(k == m + 1)
		{
			for(int j = 2;j <= m;j ++) vis[j] = 0;
			cnt[h[1]] = 0,h[1] = x,cnt[x] = 1;
			k = 2;
		}
		else 
		{
			cnt[x] = 1,cnt[h[k]] = 0;
			h[k] = x,k ++;
		}
	}
	cout << ans << "\n";
	return;
}

int main()
{
	solve();
	return 0;
} 

参考:

https://blog.csdn.net/huyang0304/article/details/82694526

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是页面替换算法(LRU)的C++代码示例: ```c++ #include <iostream> #include <unordered_map> #include <list> using namespace std; class LRUCache { private: int capacity; list<int> recent; // 双向链表,存储缓存中的key,头部为最近使用的key,尾部为最不常使用的key unordered_map<int, int> cache; // 哈希表,存储缓存的key和value unordered_map<int, list<int>::iterator> pos; // 哈希表,存储每个key在recent中的位置 public: LRUCache(int capacity) { this->capacity = capacity; } int get(int key) { if (cache.count(key) == 0) { return -1; } // 将key移动到链表头部 recent.erase(pos[key]); recent.push_front(key); pos[key] = recent.begin(); return cache[key]; } void put(int key, int value) { if (cache.count(key) == 0) { if (recent.size() == capacity) { // 缓存已满,删除最不常使用的key int least_recent = recent.back(); recent.pop_back(); cache.erase(least_recent); pos.erase(least_recent); } // 将新key插入到链表头部 recent.push_front(key); pos[key] = recent.begin(); } else { // 更新value,将key移动到链表头部 recent.erase(pos[key]); recent.push_front(key); pos[key] = recent.begin(); } cache[key] = value; // 更新缓存中的key和value } }; int main() { LRUCache cache(2); cache.put(1, 1); cache.put(2, 2); cout << cache.get(1) << endl; // 1 cache.put(3, 3); cout << cache.get(2) << endl; // -1 cache.put(4, 4); cout << cache.get(1) << endl; // -1 cout << cache.get(3) << endl; // 3 cout << cache.get(4) << endl; // 4 return 0; } ``` 在上述代码中,使用了一个双向链表来存储缓存中的key,头部为最近使用的key,尾部为最不常使用的key。同时,使用了两个哈希表来记录每个key在recent中的位置和key和value的对应关系。在get操作中,如果key不在缓存中则返回-1,否则将key移动到链表头部并返回对应的value。在put操作中,如果key不在缓存中则插入到链表头部,如果缓存已满则删除最不常使用的key,然后将新key插入到链表头部。如果key在缓存中,则更新value并将key移动到链表头部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值