ACM - ICPC

Vasya and String Codeforces - 67

2018-07-24  本文已影响2人  JesHrz

题目来源:Vasya and String

Statement

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

题意

给定一个只有a和b组成的字符串,可以修改其中k个字符,a变成b,b变成a,问同一字符最多连续出现多少次。
aabaabaa可以把一个b换成a,然后变成aaaaabaa,a连续出现了5次,答案是5。

思路

分两次进行,一次是把a变成b,一次把b变成a。每次操作的时候进行尺取(以b变成a为例),统计当前区间中有多少个b,如果不大于k则移动右端点,如果大于k则移动左端点直至区间中b的数量不大于k,每次移动的时候维护区间长度最大值。然后去两种情况的最大值,即为答案。

代码

#include <bits/stdc++.h>
using namespace std;
int n, k;
string str;
int main()
{
    while (cin >> n >> k)
    {
        cin >> str;
        int s = 0, sum = 0;
        int ans = 0;
        for (int i = 0; i < n; ++i)
        {
            if (str[i] == 'b')
                sum++;
            while (sum > k)
                if (str[s++] == 'b')
                    sum--;
            ans = max(ans, i - s + 1);
        }
        s = 0;
        sum = 0;
        for (int i = 0; i < n; ++i)
        {
            if (str[i] == 'a')
                sum++;
            while (sum > k)
                if (str[s++] == 'a')
                    sum--;
            ans = max(ans, i - s + 1);
        }
        cout << ans << endl;
    }
    return 0;
}

思路2

也是分两次进行,a变成b一次,b变成a一次,每次把不变的设为0,要变的设为1,问题转化为对一个01序列求区间和不大于k的最长子序列,尺取。

代码

#include<bits/stdc++.h>
using namespace std;
int n, k;
int a[100005];
string str;
int main()
{
    while (cin >> n >> k)
    {
        cin >> str;
        for (int i = 0; i < n; ++i)
            if (str[i] == 'a')
                a[i + 1] = 0;
            else
                a[i + 1] = 1;
        int s = 1, sum = 0;
        int ans = 0;
        for (int i = 1; i <= n; ++i)
        {
            sum += a[i];
            while (sum > k)
                sum -= a[s++];
            ans = max(ans, i - s + 1);
        }
        for (int i = 0; i < n; ++i)
            if (str[i] == 'b')
                a[i + 1] = 0;
            else
                a[i + 1] = 1;
        s = 1, sum = 0;
        for (int i = 1; i <= n; ++i)
        {
            sum += a[i];
            while (sum > k)
                sum -= a[s++];
            ans = max(ans, i - s + 1);
        }
        cout << ans << endl;
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读