zoukankan      html  css  js  c++  java
  • Codeforces Round #442 (Div. 2) B. Nikita and string DP

    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.

    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.



    emmmmmmmm,就是看在不更改各字母顺序的情况下,可以组成形如(a),(a+b),(a+b+a)的字符串的最长长度,其实就是子串拼成的a+b+a子串的最长长度,感觉。

    ps:可以删除,可以删除,可以删除!……一开始理解有点小问题……一直WA一直WA……orz

    这里是dp呀,之前好像有做过类似的?……emmmm不记得了……

    拿3个数组记录从s[0]到s[j]的符合条件的最长长度,这三个数组分别表示“a”,"ab"(“b”分到这一情况中),"aba"(“ba”,(“ab”)分到这一情况中)三种字符串

    "a":只要记录字符串中“a”的个数就好了,每次遇到“a”dp[0][j]++;

    "ab":是由上一种和该情况+b得到的,max(dp[0][j],dp[1][j]),每次遇到"b"++;

    "aba":是由前两种和该情况+a得到的,max(max(dp[0][j],dp[1][j]),dp[2][j]),每次遇到“a”++;

    最后输出最长的就好了

      

    #include<iostream> 
    #include<string>
    #include<algorithm>
    #include<map>
    using namespace std;
    string s;
    int n,m;
    int dp[3][50005];
    int main()
    {
        while (cin >> s)
        {
            dp[0][0] = 0;
            dp[1][0] = 0;
            dp[2][0] = 0;
            int l = s.length();
            for (int i = 0; i < l; i++)
            {
                dp[0][i + 1] = dp[0][i] + (s[i] == 'a');
                dp[1][i + 1] = max(dp[0][i], dp[1][i]) + (s[i] == 'b');
                dp[2][i + 1] = max(max(dp[0][i],dp[1][i]), dp[2][i]) + (s[i] == 'a');
            }
            cout << max(max(dp[0][l], dp[1][l]), dp[2][l]) << endl;
        }
        return 0;
    }
  • 相关阅读:
    Thread+Handler 线程 消息循环(转载)
    android开发之Fragment加载到一个Activity中
    Android应用程序框架之无边界设计意图
    windows系统下安装MySQL
    Java 性能优化技巧集锦
    功能完善的Java连接池调用实例
    Unicode 与 UTF 字符标准
    java内存配置
    Java Map 简介
    nginx 学习笔记(9) 配置HTTPS服务器--转载
  • 原文地址:https://www.cnblogs.com/Egoist-/p/7724876.html
Copyright © 2011-2022 走看看