Codeforces Round #877 (Div. 2) B.

题目链接:http://codeforces.com/contest/877/problem/B


Nikita and string

time limit per test2 seconds
memory limit per test256 megabytes

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

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.


解题心得:

  1. 其实是一个很简单的dp,开始还以为是一个字符串的处理,主要是要注意下,在不能够凑成aba的情况可以空出来,当是不能再可以凑成的情况下空出。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 5100;
char s[maxn];
int dp[5][maxn];
int main()
{
    scanf("%s",s);
    int len = strlen(s);
    for(int i=0;i<len;i++)
    {
        dp[0][i+1] = dp[0][i] + (s[i] == 'a');
        dp[1][i+1] = max(dp[1][i],dp[0][i]) + (s[i] == 'b');
        dp[2][i+1] = max(dp[0][i],max(dp[1][i],dp[2][i])) + (s[i] == 'a');
    }
    int Max = max(dp[0][len],max(dp[1][len],dp[2][len]));
    printf("%d",Max);
    return 0;
}
原文地址:https://www.cnblogs.com/GoldenFingers/p/9107257.html