Vasya and String CodeForces 676C
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(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
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+x−1]−sumb[i−1]<=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+x−1]−suma[i−1]<=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 ;
}