LRU Caching

本文介绍了一种模拟LRU缓存机制的方法,通过使用队列实现缓存的更新与维护,确保快速响应数据访问请求的同时,有效管理缓存空间。

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

    When accessing large amounts of data is deemed too slow, a common speed up technique is to keep a small amount of the data in a more accessible location known as a cache. The  rst time a particular piece of data is accessed, the slow method must be used. However, the data is then stored in the cache so that the next time you need it you can access it much more quickly. For example, a database system may keep data cached in memory so that it doesn't have to read the hard drive. Or a web browser might keep a cache of web pages on the local machine so that it doesn't have to download them over the network. In general, a cache is much too small to hold all the data you might possibly need, so at some point you are going to have to remove something from the cache in order to make room for new data. The goal is to retain those items that are more likely to be retrieved again soon. This requires a sensible algorithm for selecting what to remove from the cache. One simple but e ective algorithm is the Least Recently Used, or LRU, algorithm. When performing LRU caching, you always throw out the data that was least recently used. 

这里写图片描述

    As an example, let's imagine a cache that can hold up to five pieces of data. Suppose we access three pieces of data | A, B, and C. As we access each one, we store it in our cache, so at this point we have three pieces of data in our cache and two empty spots (Figure 1). Now suppose we access D and E. They are added to the cache as well,  lling it up. Next suppose we access A again. A is already in the cache, so the cache does not change; however, this access counts as a use, making A the most recently used. Now if we were to access F, we would have to throw something out to make room for F.At this point, B has been used least recently, so we throw it out and replace it with F (Figure 2). If we were now to access B again, it would be exactly as the  rst time we accessed it: we would retrieve it and store it in the cache, throwing out the least recently used data | this time C | to make room for it.

Figure 1: Cache after A, B, C
Figure 2: Cache after A, B, C, D, E, A, F
Your task for this problem is to take a sequence of data accesses and simulate an LRU cache.   When requested, you will output the contents of the cache, ordered from least recently used to most recently used

Input

    The input will be a series of data sets, one per line. Each data set will consist of an integer N and a string of two or more characters. The integer N represents the size of the cache for the data set(1<=N<=26). The string of characters consists solely of uppercase letters and exclamation marks. An upppercase letter represents an access to that particular piece of data. An exclamation mark represents a request to print the current contents of the cache.
For example, the sequence ABC!DEAF!B!means to acces A, B, and C (in that order), print the contents of the cache, access D, E, A, and F (in that order), then print the contents of the cache, then access B, and again print the contents of the cache.
The sequence will always begin with an uppercase letter and contain at least one exclamation mark.
The end of input will be signaled by a line containing only the number zero.

Output

    For each data set you should output the line Simulation S , where S is 1 for the  rst data set, 2 for the second data set, etc. Then for each exclamation mark in the data set you should output the contents of the cache on one line as a sequence of characters representing the pieces of data currently in the cache. The characters should be sorted in order from least recently used to most recently used, with least recently occuring  rst. You only output the letters that are in the cache; if the cache is not full, then you simply will have fewer characters to output (that is, do not print any empty spaces). Note that because the sequence always begins with an uppercase letter, you will never be asked to output a completely empty cache.

Sample Input

5 ABC!DEAF!B!
3 WXWYZ!YZWYX!XYXY!
5 EIEIO! 0

Sample Output

Simulation 1 ABC CDEAF DEAFB
Simulation 2 WYZ WYX WXY
Simulation 3 EIO

整个题目就是一篇阅读,讲的是高速缓存的调控机制。
考点就是在任意时刻,确定出Cache里信息的次序。因为第一想法是队列,就用queue实现了。但代码有冗余,因为一开始我以为是要按Cache里物理地址顺序输出其中信息 , 所以把下面注释号去掉运行时就会显示出,后来发现只要打印队列就可以了,就就着之前的东西用了。

思路

    当前要加入信息 info
        判断Cache是否已满
            不是 添加元素进Cache
            是
                判断当前元素是不是Cache内
                是
                    标记该元素为最新
                不是
                    从Cache踢出最旧的,并将该元素加入Cache

    既然是定长,几乎每次都是踢出当前最旧的,那么最容易想到的就是queue
    但麻烦如果该元素在Cache内要标记最新,那就要遍历整个队列了,好在题目有说最多26data,那么Cache位置肯定不大于26,那么也不容易超时.
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
char order[100000];
int Judge[10000];
char Loc[100000];
int main(void)
{
    freopen("F:\\test.txt","r",stdin);
  //  freopen("E:\\tsst.txt","w",stdout);
    int N,Count=0;
    while(~scanf("%d",&N)&&N)
    {
        scanf("%s",order+1);
        printf("Simulation %i\n",++Count);
        memset(Judge,false,sizeof(Judge));
        memset(Loc,false,sizeof(Loc));
        int now = 0;
        queue<char> Que;
        int len =strlen(order+1);
        for(int i=1;i<=len;i++)
        {
            if(order[i]!='!')
            {
                if(Judge[order[i]-'A'])
                {
                    for(int j=1;j<=now;j++)
                    {
                        char Cra = Que.front();
                        Que.pop();
                        if(Cra!=order[i]) Que.push(Cra);
                    }
                    Que.push(order[i]);
                }
                else if(now<N)   { Loc[++now] = order[i]; Judge[order[i]-'A']=now; Que.push(order[i]);}
                else
                {
                    char del = Que.front();
                    Que.pop();
                    int Locate=Judge[del-'A'];
                    Judge[del-'A'] = 0;
                    Que.push(order[i]);
                    Loc[Locate] = order[i];
                    Judge[order[i]-'A'] = Locate;
                }
                Loc[now+1]=0;
            }
                 else
               {

                    for(int j=1;j<=now;j++)
                    {
                            char Cra = Que.front();Que.pop();Que.push(Cra);
                            printf("%c",Cra);
                    }putchar('\n');

               }
/*
            printf("i==%d %c----->\n",i,order[i]);
            printf("当前各个位置的信息: ");puts(Loc+1);
            printf("当前队列: ");
            for(int j=1;j<=now;j++)
            {
                    char Cra = Que.front();Que.pop();Que.push(Cra);
                    printf("%c",Cra);
            }putchar('\n');
*/
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值