Codeforces Round #354 (Div. 2)-C

C. Vasya and String
题目链接:http://codeforces.com/contest/676/problem/C

High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.

Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?

Input

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change.

The second line contains the string, consisting of letters 'a' and 'b' only.

Output

Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

Examples
input
4 2
abba
output
4
input
8 1
aabaabaa
output
5
Note

In the first sample, Vasya can obtain both strings "aaaa" and "bbbb".

In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".

题意:给定一个长度为n的字符串,字符串只要a和b。现在可以修改k个位置的字符[a->b/ b->a],问包含相同字符的连续子串的长度最长是多少?

思路:滑动窗口。定义L,R下标,当没满足k个修改时,R向右滑,当满足K个时记录最优值然后L向右滑。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cstring>
#include<cmath>
#include<bitset>
using namespace std;
#define INF 0x3f3f3f3f
#define PI 3.14159
const int MAXN=100000+5;
char str[MAXN];
int main()
{
#ifdef kirito
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif
    int n,k;
    while(~scanf("%d%d",&n,&k)){
        scanf("%s",str);
        int tota=0,totb=0;
        int L=0,R=-1,MAXL=-1;
        while(R+1<n)
        {
            if(min(tota,totb)<=k)
            {
                R++;
                if(str[R]=='a'?tota++:totb++);
                if(min(tota,totb)<=k)
                {
                    MAXL=max(MAXL,R-L+1);
                }
            }
            else
            {
                if(str[L]=='a'?tota--:totb--);
                L++;
            }
        }
        printf("%d
",MAXL);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/kirito520/p/5550375.html