原題鏈接:
http://codeforces.com/problemset/problem/676/C
題意:
有一串a和b組成的字符串,要求最多改k的字母的情況下,最長的相同子串。
例如k=2:abba->aaaa,k=3:aaabb->bbbbb
分析:
首先可以看出如果要最長的話,改的a或b一定是連續的k個a或b,因此只要計算連續的k個a或b夾在中間和兩邊的字母個數,當然包括改的字母。所以只要維護一個k大小的窗口,不停向右滑動,來計算出每個窗口的答案,取最大值。時間複雜度爲O(n)。
代碼:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<string>
#include<queue>
#include<cmath>
#include<stack>
#include<cctype>
#include<list>
#define ll long long
#define ull unsigned long long
using namespace std;
const int maxn=100010;
const int inf=1<<30;
char str[maxn];
int a[maxn];//存a和b在原數組的位置,通過可以算出所需求的字母的個數
int b[maxn];
int main()
{
//#define DEBUG
#ifdef DEBUG
freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
#endif
int n,k;
while(~scanf("%d%d",&n,&k)){
scanf("%s",str+1);
int an=0,bn=0;
for(int i=1;i<=n;i++){
if(str[i]=='a')a[++an]=i;
else b[++bn]=i;
}
a[0]=b[0]=0;//左右邊界處理
a[an+1]=b[bn+1]=n+1;
if(k>=an||k>=bn){
printf("%d\n",n);
continue;
}
int ans=1;
int res;
if(k<an){
res=a[k+1]-1;
ans=max(res,ans);
for(int i=2;i<=an-k+1;i++){
res-=a[i-1]-a[i-2];//去掉前面一段
res+=a[i+k]-a[i+k-1];//加上後面一段
ans=max(res,ans);//更新
}
}
if(k<bn){
res=b[k+1]-1;
ans=max(res,ans);
for(int i=2;i<=bn-k+1;i++){
res-=b[i-1]-b[i-2];
res+=b[i+k]-b[i+k-1];
ans=max(res,ans);
}
}
printf("%d\n",ans);
}
return 0;
}