Codeforces Round #442 (Div. 2) B. Nikita and string

来源:互联网 发布:星星知我心演员胡家玮 编辑:程序博客网 时间:2024/05/21 02:21

B. Nikita and string

Problem Statement

    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

Example 1
    Input
        abba
    Output
        4
Example 2
    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.

题意

    给定一个字符串,只有a,b两个字符,现在可以删一些字符,使得剩下的字符可以裁剪成三段,第一段和第三段只含a, 第二段只含b。问删除后的字符串最长可以是多长。

思路

    这题刚开始没想到很好的方法去做,后来发现长度其实只有5000,我就记录了一下a个数的前缀和与后缀和,还有b个数的前缀和,然后n^2枚举断点,就是从哪开始全是a和全是b的字符串分开,然后……因为枚举的时候少加了个1,就GG了..

Code

#pragma GCC optimize(3)#include<bits/stdc++.h>using namespace std;typedef long long ll;bool Finish_read;template<class T>inline void read(T &x) {    Finish_read=0;x=0;int f=1;char ch=getchar();    while(!isdigit(ch)){if(ch=='-')f=-1;if(ch==EOF)return;ch=getchar();}    while(isdigit(ch))x=x*10+ch-'0',ch=getchar();    x*=f;Finish_read=1;}template<class T>inline void print(T x) {    if(x/10!=0)        print(x/10);    putchar(x%10+'0');}template<class T>inline void writeln(T x) {    if(x<0)        putchar('-');    x=abs(x);    print(x);    putchar('\n');}template<class T>inline void write(T x) {    if(x<0)        putchar('-');    x=abs(x);    print(x);}/*================Header Template==============*/string s;int ans=0,cnt;int sa[5005],fa[5005],b[5005];int main() {    cin>>s;    int n=s.length();    for(int i=0;i<n;i++) {        sa[i+1]=sa[i];        b[i+1]=b[i];         if(s[i]=='a')            sa[i+1]++;        else            b[i+1]++;    }    for(int i=n-1;i>=0;i--) {        fa[i+1]=fa[i+2];        if(s[i]=='a')            fa[i+1]++;    }    for(int i=1;i<=n+1;i++)        for(int j=i;j<=n+1;j++)            ans=max(ans,sa[i-1]+b[j]-b[i-1]+fa[j+1]);    printf("%d\n",ans);    return 0;}
阅读全文
1 0