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
思路
题意:
给定长度为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;
}
┆ 凉 ┆ 暖 ┆ 降 ┆ 等 ┆ 幸 ┆ 我 ┆ 我 ┆ 里 ┆ 将 ┆ ┆ 可 ┆ 有 ┆ 谦 ┆ 戮 ┆ 那 ┆ ┆ 大 ┆ ┆ 始 ┆ 然 ┆
┆ 薄 ┆ 一 ┆ 临 ┆ 你 ┆ 的 ┆ 还 ┆ 没 ┆ ┆ 来 ┆ ┆ 是 ┆ 来 ┆ 逊 ┆ 没 ┆ 些 ┆ ┆ 雁 ┆ ┆ 终 ┆ 而 ┆
┆ ┆ 暖 ┆ ┆ 如 ┆ 地 ┆ 站 ┆ 有 ┆ ┆ 也 ┆ ┆ 我 ┆ ┆ 的 ┆ 有 ┆ 精 ┆ ┆ 也 ┆ ┆ 没 ┆ 你 ┆
┆ ┆ 这 ┆ ┆ 试 ┆ 方 ┆ 在 ┆ 逃 ┆ ┆ 会 ┆ ┆ 在 ┆ ┆ 清 ┆ 来 ┆ 准 ┆ ┆ 没 ┆ ┆ 有 ┆ 没 ┆
┆ ┆ 生 ┆ ┆ 探 ┆ ┆ 最 ┆ 避 ┆ ┆ 在 ┆ ┆ 这 ┆ ┆ 晨 ┆ ┆ 的 ┆ ┆ 有 ┆ ┆ 来 ┆ 有 ┆
┆ ┆ 之 ┆ ┆ 般 ┆ ┆ 不 ┆ ┆ ┆ 这 ┆ ┆ 里 ┆ ┆ 没 ┆ ┆ 杀 ┆ ┆ 来 ┆ ┆ ┆ 来 ┆

浙公网安备 33010602011771号