Day5 简单hash,list

本文介绍了一种基于链表实现的LRU缓存机制,通过C++代码详细展示了当缓存命中或未命中时的具体操作流程。该实现考虑了缓存大小限制,并在缓存满时自动移除最久未使用的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: 点击打开链接
代码:
#include<iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
const int maxn = 20005;
int cache_size=0;

int n,m,k=1;
int pos[maxn];
int first = 1,last = maxn;
string s;
map<string, int> mp;

struct node{
    int num,pre,nxt;
}cache_list[maxn];

bool is_full(){
    if(cache_size == m) return true;
    return false;
}

bool is_in(int x){
    if(pos[x]<first){
        return false;
    }
    return true;
}

void add(int x){
    int p = cache_list[last].pre+1;
    pos[x] = p;
    cache_list[cache_list[last].pre].nxt = p;
    cache_list[p].pre = cache_list[last].pre;
    cache_list[p].nxt = last;
    cache_list[last].pre = p;
    cache_size++;
}

void del(int x){
    int p = pos[x];
    if(p == first){
        first = cache_list[first].nxt;
    }
    else {
        int pre = cache_list[p].pre;
        int nxt = cache_list[p].nxt;
        cache_list[pre].nxt = nxt;
        cache_list[nxt].pre = pre;
    }

    cache_size--;
}

void update(int x){
    del(x);
    add(x);
}

int main(){
    cin>>n>>m;
    memset(pos,-1,sizeof(pos));
    for(int i=1; i<=n; i++){
        cin>>s;
        if(mp.count(s) == 0){
            mp[s] = k++;
        }

        int x = mp[s];
        if(is_in(x)){
            printf("Cache\n");
            update(x);
        }else {
            printf("Internet\n");
            if(is_full()){
                first = cache_list[first].nxt;
                cache_size--;
            }
            add(x);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值