欢迎访问~原文出处——博客园-zhouzhendong
去博客园看该题解
题目传送门 - BZOJ1826
题意概括
Cache中有m个储存单元,接下来有n个访问地址,每个地址用一个数字表示。访问每一个地址,就要使用一次Cache的一个储存单元,当你选择某一个储存单元时,如果这个储存单元原来不是该地址,那么就发生一次遗失,并把该储存单元的值改为该地址;如果原来这个储存单元就是这个地址,那么不发生遗失且可以直接访问该地址。现在有n个地址访问请求依次输入,每次,你可以选择把地址放在哪一个存储单元,求最少的遗失次数(一开始都没有存储)。
题解
贪心策略:当有空的存储空间时,先放到空的里面,并记录一次遗失;当每个存储空间都已有记录时,如果该地址已经存在,则直接使用,否则每次替换当前占用的所有地址中下一次出现最晚的,并记录一次遗失。
对于“下一次出现时间最晚的”,我们用大根堆来维护。
代码
#include <cstring>#include <algorithm>#include <cstdio>#include <cmath>#include <cstdlib>#include <vector>using namespace std;const int N=100000+5;const int inf=1<<28;vector <int> num[N];int n,m,a[N],hash[N],hs,size[N],link[N],cnt,ans,heap[N],top,pt[N];bool f[N];void read(int &x){char ch=getchar();while (!(‘0‘<=ch&&ch<=‘9‘))ch=getchar();x=0;while (‘0‘<=ch&&ch<=‘9‘){x=x*10+ch-48;ch=getchar();}}int find(int x){int le=1,ri=hs,mid;while (le<=ri){mid=(le+ri)/2;if (hash[mid]==x)return mid;if (hash[mid]<x)le=mid+1;if (hash[mid]>x)ri=mid-1;}}void up_sift(int x,int top){int i=x,j;while (i>1){j=i/2;if (num[heap[i]][link[heap[i]]]<num[heap[j]][link[heap[j]]])break;swap(pt[heap[i]],pt[heap[j]]);swap(heap[i],heap[j]);i=j;}}void down_sift(int x,int top){int i=x,j=i*2;while (j<=top){if (j<top&&num[heap[j]][link[heap[j]]]<num[heap[j+1]][link[heap[j+1]]])j++;if (num[heap[i]][link[heap[i]]]>num[heap[j]][link[heap[j]]])break;swap(pt[heap[i]],pt[heap[j]]);swap(heap[i],heap[j]);i=j,j=i*2;}}int main(){scanf("%d%d",&n,&m);for (int i=1;i<=n;i++)scanf("%d",&a[i]),hash[i]=a[i];sort(hash+1,hash+1+n);hs=1;for (int i=2;i<=n;i++)if (hash[i]!=hash[i-1])hash[++hs]=hash[i];for (int i=1;i<=hs;i++)num[i].clear();for (int i=1;i<=n;i++)num[find(a[i])].push_back(i);for (int i=1;i<=hs;i++)size[i]=num[i].size(),link[i]=0;for (int i=1;i<=hs;i++)num[i].push_back(inf);memset(f,0,sizeof f),memset(heap,0,sizeof heap),memset(pt,0,sizeof pt);cnt=ans=top=0;for (int i=1;i<=n;i++){int pos=find(a[i]);link[pos]++;if (f[pos]){up_sift(pt[pos],top);continue;}ans++,f[pos]=1;if (cnt<m){cnt++,heap[++top]=pos,pt[pos]=top;up_sift(top,top);}else {f[heap[1]]=0,pt[heap[1]]=0;heap[1]=pos,pt[pos]=1;down_sift(1,top);}}printf("%d",ans);return 0;}
BZOJ1826 [JSOI2010]缓存交换 堆 贪心
原文地址:http://www.cnblogs.com/zhouzhendong/p/7533296.html