BZOJ1826 [JSOI2010]缓存交换 堆 贪心
欢迎访问~原文出处——博客园-zhouzhendong
去博客园看该题解
题目传送门 - BZOJ1826
题意概括
Cache中有m个储存单元,接下来有n个访问地址,每个地址用一个数字表示。访问每一个地址,就要使用一次Cache的一个储存单元,当你选择某一个储存单元时,如果这个储存单元原来不是该地址,那么就发生一次遗失,并把该储存单元的值改为该地址;如果原来这个储存单元就是这个地址,那么不发生遗失且可以直接访问该地址。现在有n个地址访问请求依次输入,每次,你可以选择把地址放在哪一个存储单元,求最少的遗失次数(一开始都没有存储)。
题解
贪心策略:当有空的存储空间时,先放到空的里面,并记录一次遗失;当每个存储空间都已有记录时,如果该地址已经存在,则直接使用,否则每次替换当前占用的所有地址中下一次出现最晚的,并记录一次遗失。
对于“下一次出现时间最晚的”,我们用大根堆来维护。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | #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; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术