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

传送门

Description

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.

Sample Input

4 2
abba
8 1
aabaabaa

Sample Output

4
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的字符串,可更换字符串中的字母k次,问字符串的子串中,字母相同的子串的最大长度。

题解:

尺取法,然后依次更新最大值

 

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100005;
char str[maxn];
bool flag[maxn];

int main()
{
	//freopen("input.txt","r",stdin);
	int n,k,res = 0;
	memset(flag,false,sizeof(flag));
	queue<int>que1,que2;
	scanf("%d%d%s",&n,&k,str);
	int len = strlen(str);
	int s = 0,t = 0,sum = 0;
	for (;;)
	{
		if (t >= len)	break;
		while (t < len && sum <= k)
		{
			if (str[t] == 'b')
			{
				if (!flag[t])	flag[t] = true,que1.push(t);
				t++,sum++;
			}	
			else	t++;
		}
		if (sum > k)	sum--,t--;
		if (t > len)	break;
		res = max(res,t - s);
		sum--;
		s = que1.front()+1;
		que1.pop();
	}
	s = 0,t = 0,sum = 0;
	memset(flag,false,sizeof(flag));
	for (;;)
	{
		if (t >= len)	break;
		while (t < len && sum <= k)
		{
			if (str[t] == 'a')
			{
				if (!flag[t])	flag[t] = true,que2.push(t);
				t++,sum++;
				
			}
			else	t++;
		}
		if (sum > k)	sum--,t--;
		if (t > len)	break;
		res = max(res,t - s);
		sum--;
		s = que2.front()+1;
		que2.pop();
	}
	printf("%d\n",res);
	return 0;
}

  

posted @ 2017-04-21 16:28  zxzhang  阅读(192)  评论(0)    收藏  举报