codeforces 877B

题目链接:

考虑维护三个信息:

[pre[i]:i 位置及之前 a 的数量 ]

[suf[i]: i 位置及之后 a 的数量 ]

[sumb[i]: i 位置及之前 b 的数量 ]

枚举 b 的区间,加上两边 a 序列的长度即可 注意三个序列都可以为空

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 5010;

int n;
int pre[maxn],suf[maxn],sumb[maxn],mid[maxn][maxn];

char s[maxn];

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	scanf("%s",s+1);
	
	n = strlen(s+1);
	for(int i=1;i<=n;++i){
		if(s[i] == 'a'){
			pre[i] = pre[i-1] + 1;
			sumb[i] = sumb[i-1];
		}
		else if(s[i] == 'b'){
			sumb[i] = sumb[i-1] + 1;
			pre[i] = pre[i-1];
		}
		else {
			sumb[i] = sumb[i-1];
			pre[i] = pre[i-1];
		}
	}
	
	for(int i=n;i>=1;--i){
		if(s[i] == 'a') suf[i] = suf[i+1] + 1;
		else suf[i] = suf[i+1];
	}
	
	int ans = 0;
	for(int i=0;i<=n;++i){
		for(int j=i+1;j<=n+1;++j){
			if(i+1 <= j-1) ans = max(ans,pre[i] + suf[j] + sumb[j-1] - sumb[i]);
			else ans = max(ans,pre[i] + suf[j]);
		}
	}
	printf("%d
",ans);
	
	return 0;
}
原文地址:https://www.cnblogs.com/tuchen/p/13831323.html