考虑二分最终答案 ,计算最小修改次数。
分两部分计算:两个串重叠的和不重叠的。
对于不重叠的,预处理 ,计算答案时枚举两个串的起始点 ,则答案为 。
对于重叠的,枚举 ,则 可 算出。注意到模 余数相同时字符一定相同,考虑模 分类,每一类维护字符出现次数 ,和 ,出现次数最多的字符出现次数 ,以及总的答案 。
变到 时,改变的只有 这两个位置,可 修改。 的情况可以枚举处理。计算完之后清空,对于每个 都是 的。总时间复杂度 。常数有点大。
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;
}