B. Nikita and string
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?
Input
The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".
Output
Print a single integer — the maximum possible size of beautiful string Nikita can get.
Input
abba
Output
4
题意:给出一个字符串,这个字符串长度最大是5000,并且规定只有ab组成,现在问你,能不能将这个字符串分成三部分,第一和第三部分只有a或者是空,第二部分由b或者空组成。问你能不能分成这样的形式,如果能那么最长的长度是多少。
思路:暴力+模拟【只有5中情况。分别是a,b,ab,ba,aba。那么我们只要统计出这五种情况的最大的长度,最后我们取其中最大的就好了】
AC代码:{调了挺久的QAQ 菜是原罪}
1 #include<bits/stdc++.h> 2 3 using namespace std; 4 #define N 1200000 5 set<char> sss; 6 struct str{ 7 int type; 8 int num; 9 int qian;// 前缀 10 int hou;// 后缀 11 }st[N]; 12 int main(){ 13 string str; 14 cin>>str; 15 int suma=0; 16 int sumb=0; 17 int cnt=0; 18 int add=1; 19 for(int i=0;i<=str.size();i++){ 20 if(str[i]==‘a‘&&i!=str.size()){ 21 suma++; 22 }else if(str[i]==‘b‘&&i!=str.size()){ 23 sumb++; 24 } 25 if(str[i]!=str[i+1]){ 26 st[cnt].type=str[i]-‘a‘; 27 st[cnt++].num=add; 28 add=1; 29 }else{ 30 add++; 31 } 32 if(i!=str.size()) 33 sss.insert(str[i]); 34 } 35 if(sss.size()==1){ // a,b情况 36 printf("%d\n",str.size()); 37 return 0; 38 } 39 int sa=0; 40 int sb=0; 41 for(int i=0;i<cnt;i++){// 前缀 42 if(st[i].type==1){ 43 st[i].qian=sa; 44 }else{ 45 st[i].qian=sb; 46 } 47 if(st[i].type==1){ // 类型:B 48 sb+=st[i].num; 49 }else{ 50 sa+=st[i].num; 51 } 52 } 53 sa=0; 54 sb=0; 55 for(int i=cnt-1;i>=0;i--){ 56 if(st[i].type==1){ 57 st[i].hou=sa; 58 }else{ 59 st[i].hou=sb; 60 } 61 if(st[i].type==1){ // 类型:B 62 sb+=st[i].num; 63 }else{ 64 sa+=st[i].num; 65 } 66 } 67 /* 68 for(int i=0;i<cnt;i++){ 69 printf("%d ",st[i].num); 70 } 71 printf("\n"); 72 for(int i=0;i<cnt;i++){ 73 printf("%d %d \n",st[i].qian,st[i].hou); 74 } 75 */ 76 int ans=max(suma,sumb); 77 78 for(int i=0;i<cnt;i++){ 79 if(st[i].type==1){ 80 ans=max(ans,st[i].num+st[i].hou+st[i].qian); 81 int add=0; 82 for(int j=i+2;j<cnt;j+=2){ 83 add+=st[j].num; 84 ans=max(ans,st[i].qian+add+st[i].num+st[j].hou); 85 } 86 } 87 88 } 89 for(int i=0;i<cnt;i++){ 90 ans=max(ans,st[i].num+st[i].hou); 91 int res=0; 92 for(int j=i+2;j<cnt;j+=2){ 93 res+=st[j].num; 94 ans=max(ans,st[i].num+res+st[j].hou); 95 } 96 } 97 98 cout<<ans; 99 return 0; 100 } 101 102 /* 103 bbabbbbbaaba 104 aabaaaaabbab 105 aaaabaabbbbbaaabaaaa 106 a,b,ab,ba,aba 107 108 109 bb a bbbbb aa b a 110 111 2 1 5 2 1 1 112 113 114 115 116 */