codefforces 877B

B. Nikita and string
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Examples
input
abba
output
4
input
bab
output
2
Note
It the first sample the string is already beautiful.

In the second sample he needs to delete one of "b" to make it beautiful.

(这一题做的时候,一直不理解 without changing their order 是什么意思,我的理解是只能从最左边和最右边删除字符。。。

题意:给一个只含字符a,b的字符串st,要求从中删除任意的字符,求其满足aba的格式的最长字符串长度(左边和右边都是只有a的字符串,中间是只有b的字符串,当然也可以为空,不懂的话可根据样例理解一下

解题思路:当时想的是记录a和b的前缀和,然后暴力跑b的位置。(咩做出来。。。是的我又只做出来一题

     赛后补题看到竟然可以用dp做,看一看代码,恍然大悟啊。

     我们依然是dp的思想,对每一个元素进行分析:

     如果是‘a’,那他要么是a串的,要么是c串的;

          如果是a串的,直接a++;

          如果是c串的,他有可能是b串后的第一个c,就是b+1,还有可能是依然接在c的后面,那就是c+1,取其中最长的就是当前最佳的c的长度

     如果是‘b’,那他肯定是b串的,这时候和c一样,有两种情况,可能是a串后面的第一个b,就是a+1,还有可能是依然接在b的后面,就是b+1,取其中最长的就是当前最佳的b的长度

     (这个特别像之前做的一道题,每一个元素要么是前一个串的后续,要么是后一个串的开头

ac代码:

 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4     string s;
 5     cin>>s;
 6     int a=0,b=0,c=0;
 7     for(int i=0;i<s.size();++i) {
 8         if(s[i]=='a') {
 9             a++;
10             c=max(b+1,c+1);
11         }
12         else b=max(a+1,b+1);
13     }
14     cout<<max(b,c);
15     return 0;
16 }
View Code
原文地址:https://www.cnblogs.com/zmin/p/7724069.html