(尺取法)Codeforces 676C - Vasya and String

原题链接:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值