Vasya and String CodeForces 676C 前缀和+二分

Vasya and String CodeForces 676C

传送门:https://codeforces.com/problemset/problem/676/C

Description
High school student Vasya got a string of length n n 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 k 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 n n and k ( 1   ≤   n   ≤   100   000 ,   0   ≤   k   ≤   n ) k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) k(1n100000,0kn) — 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 k k characters.

题意
给出一串长度为 n n n的字符串,字符串中只有 ‘ a ’ ‘a’ a或者 ′ b ′ 'b' b,我们可以改变 k k k 次字母,我们可以得到的相同的连续子串最长有多长。

思路
假设 x x x是猜测的能得到的最长的连续的子串长度, s s s是真实的能得到的最长的连续的子串长度,那么对于所有可行的 x x x,都有 x < = s x<=s x<=s
f ( x ) = ( x < = s ? 1 : 0 ) f(x)=(x<=s?1:0) f(x)=(x<=s?1:0)具有单调性,所以可以二分找答案。
s u m a suma suma数组和 s u m b sumb sumb数组记录在 1 1 1 i i i 这段区间里有多少个 a a a(有多少个 b b b) , 然后二分找答案。在 c h e c k check check函数中,我们可以像比着一把尺子一样检测,看对于当前的答案 x x x 是否合法。如果 i i i i + x i+x i+x 这个区间合法,即 i i i i + x i+x i+x 可以构成连续的一串 a a a 或者连续的一串 b b b,那么一定有
连续的a成立 s u m b [ i + x − 1 ] − s u m b [ i − 1 ] < = k sumb[i+x-1]-sumb[i-1]<=k sumb[i+x1]sumb[i1]<=k
意思是 i i i i + x i+x i+x 这个区间的 b b b 可以全部被替换成 a a a
同理,如果连续的 b b b 成立 s u m a [ i + x − 1 ] − s u m a [ i − 1 ] < = k suma[i+x-1]-suma[i-1]<=k suma[i+x1]suma[i1]<=k
意思是 i i i i + x i+x i+x 这个区间的 a a a 可以全部被替换成 b b b

代码

#include<iostream>
using namespace std ;
#define ll long long
const ll N = 1e5+9 ;
void updata( ll &a , ll b ){if(b>a)a=b;}
string s ; ll n , k ;
ll suma[ N ] , sumb[ N ] ;
bool check( ll maxn ){
    for( int i = 1 ; i + maxn - 1 <= n ; i ++ ){
        if( suma[ i + maxn - 1 ] - suma[ i - 1 ] <= k || sumb[ i + maxn - 1 ] - sumb[ i - 1 ] <= k ) return 1 ;
    }
    return 0 ;
}
int main(){
    cin >> n >> k >> s ; s = "?"+s ;
    for( int i = 1 ; i <= n ; i ++ ){
        if( s[ i ] == 'a' ){ suma[ i ] = suma[ i - 1 ] + 1 ; sumb[ i ] = sumb[ i - 1 ] ; }
        else { suma[ i ] = suma[ i - 1 ] ; sumb[ i ] = sumb[ i - 1 ] + 1 ; }
    }
    ll l , r , mid , ans = -1 ;
    l = 1 , r = 2*n+10000 ;
    while( l <= r ){
        mid = l + r >> 1 ;
        ll f = check( mid ) ;
        if( f ) { l = mid + 1 ; updata( ans , mid ) ; }
        else r = mid - 1 ;
    }
    cout << ans << "\n" ;
return 0 ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值