codeforces676C. Vasya and String
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?
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.
OutputPrint the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k
4 2 abbaOutput
4Input
8 1 aabaabaaOutput
5
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".
題意:給你一個字串,只有a,b,最多k此操作,每次操作可以任意改變一個字元,求最長的連續相同字元長度
思路:直接用佇列計入要改的字元的位置, 然後跑一邊就可以了,複雜度O(2 * n);
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
const int inf = 2147483647;
const double PI = acos(-1.0);
const double e = 2.718281828459;
const int mod = 1000000007;
typedef long long LL;
#pragma comment(linker, "/STACK:102400000,102400000")
//freopen("in.txt","r",stdin); //輸入重定向,輸入資料將從in.txt檔案中讀取
//freopen("out.txt","w",stdout); //輸出重定向,輸出資料將儲存在out.txt檔案中cin
char s[100005];
queue<int>sq;
int main()
{
int n, k, i, j;
while (cin >> n >> k)
{
cin >> s + 1;
int mmax = 0;
int last = 1;
int ans = 0;
while (!sq.empty())
sq.pop();
for (i = 1; i <= n; ++i)
{
if (s[i] == 'b')
{
if (sq.size() < k)
{
sq.push(i);
mmax = max(mmax, i - last + 1);
}
else
{
if (sq.size() != 0)
{
last = sq.front() + 1;
sq.pop();
sq.push(i);
}
else
last = i + 1;
}
ans = 1;
}
else
mmax = max(mmax, i - last + 1);
}
//cout << ans << endl;
if (!ans)
mmax = n;
while (!sq.empty())
sq.pop();
ans = 0;
last = 1;
for (i = 1; i <= n; ++i)
{
if (s[i] == 'a')
{
//mmax = max(mmax, i - 1 - last + 1);
if (sq.size() < k)
{
sq.push(i);
mmax = max(mmax, i - last + 1);
}
else
{
if (sq.size() != 0)
{
last = sq.front() + 1;
sq.pop();
sq.push(i);
}
else
last = i + 1;
}
ans = 1;
}
else
mmax = max(mmax, i - last + 1);
}
if (!ans)
mmax = n;
cout << mmax << endl;
}
}