Codeforces Round #354 (Div. 2) C. Vasya and String

题目大意:有一个(a|b)^N的由a和b构成的长度为N的字符串,允许修改其中k位。问能构成的最长的全为a或全为b的子串的长度最长为多少。

思路,用两个队列分别保存前K+1个a和b的位置,以i为结尾的最长的子串的长度就是i减去队列头元素的值。

#include <iostream>
#include <cstdio>
#include <memory.h>
#include <queue>
using namespace std;
int main(int argc, const char * argv[]) {
    char input[1000005];
    int N,K,res1;
    queue<int> posa;
    queue<int> posb;
    scanf("%d%d",&N,&K);
    for(int i=1;i<=N;i++){
        cin>>input[i];
    }
    posa.push(0);//预存0的位置,实际输入下标从1开始
    posb.push(0);
    res1=0;
    for(int i=1;i<=N;i++){
        if(input[i]=='a'){
            posa.push(i);
            if(posa.size()>K+1)
                posa.pop();
        }
        else{
            posb.push(i);
            if(posb.size()>K+1)
                posb.pop();
        }
        res1=max(res1,i-posb.front());
        res1=max(res1,i-posa.front());
    }
    printf("%d",res1);
    return 0;
}

 

posted on 2016-06-01 23:29  insaneman  阅读(113)  评论(0编辑  收藏  举报

导航