洛谷4404 [JSOI2010]缓存交换(贪心)(优先队列)

版权声明:本文为博主原创文章,未经博主允许不得转载,除非先点了赞。 https://blog.csdn.net/A_Bright_CH/article/details/83063187

题目

在计算机中,CPU只能和高速缓存Cache直接交换数据。当所需的内存单元不在Cache中时,则需要从主存里把数据调入Cache。此时,如果Cache容量已满,则必须先从中删除一个。 例如,当前Cache容量为3,且已经有编号为10和20的主存单元。 此时,CPU访问编号为10的主存单元,Cache命中。 接着,CPU访问编号为21的主存单元,那么只需将该主存单元移入Cache中,造成一次缺失(Cache Miss)。 接着,CPU访问编号为31的主存单元,则必须从Cache中换出一块,才能将编号为31的主存单元移入Cache,假设我们移出了编号为10的主存单元。 接着,CPU再次访问编号为10的主存单元,则又引起了一次缺失。我们看到,如果在上一次删除时,删除其他的单元,则可以避免本次访问的缺失。 在现代计算机中,往往采用LRU(最近最少使用)的算法来进行Cache调度——可是,从上一个例子就能看出,这并不是最优的算法。 对于一个固定容量的空Cache和连续的若干主存访问请求,聪聪想知道如何在每次Cache缺失时换出正确的主存单元,以达到最少的Cache缺失次数。

特性

当要删除某一元素时,删除队列中下一个相同元素最远的是最优的。

题解

贪心+优先队列
在二叉堆中存入所有元素的下一个位置,每次取出堆头,判断它是否是旧元素,不是的话把它弹出。

代码

#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<int,int> pii;//(距离,标号) 
const int maxn=100010;
int n,m;
int a[maxn],b[maxn];
int next[maxn],last[maxn];

priority_queue<pii/*,vector<pii>,greater<pii> */> q;bool v[maxn];//优先队列默认大根堆 

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),b[i]=a[i];
    sort(b+1,b+n+1);int tot=unique(b+1,b+n+1)-(b+1);
    memset(last,63,sizeof(last));
    for(int i=n;i>=1;i--)
    {
        a[i]=lower_bound(b+1,b+tot+1,a[i])-b;
        next[i]=last[a[i]];
        last[a[i]]=i;
    }
    //先填满Cache
    int cnt=0,ans=0,i;
    for(i=1;i<=n;i++)
    {
        if(v[a[i]])
        {
            q.push(pii(next[i],a[i]));
        }
        else
        {
            v[a[i]]=true;
            q.push(pii(next[i],a[i]));
            ans++;
            cnt++;if(cnt==m){i++;break;}
        }
    }
    //现在要考虑弹出操作了
    for(;i<=n;i++)
    {
        if(v[a[i]])
        {
            q.push(pii(next[i],a[i]));
        }
        else
        {
            pii tp=q.top();q.pop();
            while(!v[tp.second]) tp=q.top(),q.pop();
            int del=tp.second;
            v[del]=false;
            v[a[i]]=true;
            q.push(pii(next[i],a[i]));
            ans++;
        }
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/A_Bright_CH/article/details/83063187