One day Nikita found the string containing letters "a" and "b" only.
Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".
Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?
The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".
Print a single integer — the maximum possible size of beautiful string Nikita can get.
Examples
abba
4
bab
2
Note
It the first sample the string is already beautiful.
/*************************************************
题意:
给定一个只含有'a'和'b'的字符串,要求从这个字符串中进行字符删减,使得该字符串能够由三个字符串构成。
第一个和第三个串只能含有'a'或者为空,第二个字符串只能含有'b'或者为空。问使得满足上述条件的最长的字符串长度。 分两种情况,一种不含'b',最大长度就是原长。
第二种情况含有'b',利用前缀和后缀,保存每个'b'所在位置前后'a'的个数,然后利用双重for暴力历遍任意1-2个'b',计算最大长度
Max=max(Max,head_a[i]+tot_b+back_a[j]);
其中tot_b是i,j之间'b'的个数。
***************************************************/
#include "cstdio"
#include "cstring"
const int MX = + ;
char str[MX];
int f[MX], b[MX];
int b_list[MX]; int main() {
memset(str,,sizeof(str));
while(~scanf("%s",str)) {
memset(f,,sizeof(f));
memset(b,,sizeof(b));
memset(b_list,,sizeof(b_list));
int tot = ;
int sum = ;
int len = strlen(str);
for(int i = ; i < len; i++) {
if(str[i] == 'b') {
b_list[tot++] = i;
} else sum++;
f[i]=sum;
}
sum=;
for(int i = len-; i >= ; i--) {
if(str[i] == 'a') sum++;
b[i] = sum;
}
if(tot==){
printf("%d\n",len);
continue;
}
int mx=-;
for(int i = ; i < tot; i++) {
for(int j = i; j < tot; j++) {
sum = f[b_list[i]]+b[b_list[j]]++j-i;
mx=mx>sum?mx:sum;
}
}
memset(str,,sizeof(str));
printf("%d\n",mx);
}
return ;
}