7/2模拟赛A题解

· · 题解

考虑二分最终答案 L,计算最小修改次数。

分两部分计算:两个串重叠的和不重叠的。

对于不重叠的,预处理 sum_{i,j}=\sum_{k=1}^{j} [s_k=s_i+k],计算答案时枚举两个串的起始点 i,j,则答案为 sum_{j-i,j+L-1}-sum_{j-i,i-1}。

对于重叠的,枚举 d=j-i,i,则 j 可 O(1) 算出。注意到模 d 余数相同时字符一定相同,考虑模 d 分类,每一类维护字符出现次数 cnt_c,和 cnt2_i=\sum [cnt_c=i],出现次数最多的字符出现次数 ma,以及总的答案 ans。

AC代码: ``` #include<bits/stdc++.h> using namespace std; int n,k,l,r,f[3010][3010],cnt[3010][130],st[3010][3010],ma[3010],sum; char s[3010]; int main(){ scanf("%d%s",&k,s+1),l=k+1,r=n=strlen(s+1),r--; for(int w=1;w<=n;w++)for(int x=1;w+x<=n;x++)f[x][w]=f[x][w-1]+(s[w]!=s[w+x]); while(l<r){ int m=(l+r+1)/2,ans=1e9; for(int w=1;w<=n-m+1;w++)for(int x=w+m;x+m-1<=n;x++)ans=min(ans,f[x-w][w+m-1]-f[x-w][w-1]); for(int L=1;L<m&&m+L<=n;L++){ for(int w=0;w<L;w++)st[w][0]=128,ma[w]=0; for(int w=1;w<=m+L;w++){ int p=w%L; st[p][cnt[p][s[w]]]--,cnt[p][s[w]]++,st[p][cnt[p][s[w]]]++,sum-=ma[p],ma[p]=max(ma[p],cnt[p][s[w]]),sum+=ma[p]; } ans=min(ans,m+L-sum); for(int w=2,x=w+L;x+m-1<=n;w++,x++){ int p=(w-1)%L; st[p][cnt[p][s[w-1]]]--,cnt[p][s[w-1]]--,st[p][cnt[p][s[w-1]]]++; if(!st[p][ma[p]])ma[p]--,sum--; p=(x+m-1)%L; st[p][cnt[p][s[x+m-1]]]--,cnt[p][s[x+m-1]]++,st[p][cnt[p][s[x+m-1]]]++,sum-=ma[p],ma[p]=max(ma[p],cnt[p][s[x+m-1]]),sum+=ma[p]; ans=min(ans,m+L-sum); } sum=0; for(int w=1;w<=n;w++)st[w%L][cnt[w%L][s[w]]]=0,cnt[w%L][s[w]]=0; } if(ans<=k)l=m; else r=m-1; } printf("%d",l); return 0; } ```