Nikita and string [思维-暴力] ACM
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'的个数。 ***************************************************/
1 #include "cstdio" 2 #include "cstring" 3 const int MX = 5000 + 10; 4 char str[MX]; 5 int f[MX], b[MX]; 6 int b_list[MX]; 7 8 int main() { 9 memset(str,0,sizeof(str)); 10 while(~scanf("%s",str)) { 11 memset(f,0,sizeof(f)); 12 memset(b,0,sizeof(b)); 13 memset(b_list,0,sizeof(b_list)); 14 int tot = 0; 15 int sum = 0; 16 int len = strlen(str); 17 for(int i = 0; i < len; i++) { 18 if(str[i] == 'b') { 19 b_list[tot++] = i; 20 } else sum++; 21 f[i]=sum; 22 } 23 sum=0; 24 for(int i = len-1; i >= 0; i--) { 25 if(str[i] == 'a') sum++; 26 b[i] = sum; 27 } 28 if(tot==0){ 29 printf("%d\n",len); 30 continue; 31 } 32 int mx=-1; 33 for(int i = 0; i < tot; i++) { 34 for(int j = i; j < tot; j++) { 35 sum = f[b_list[i]]+b[b_list[j]]+1+j-i; 36 mx=mx>sum?mx:sum; 37 } 38 } 39 memset(str,0,sizeof(str)); 40 printf("%d\n",mx); 41 } 42 return 0; 43 }