CodeForces - 877B 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 000containing only lowercase English letters "a" and "b".

Output

Print a single integer — the maximum possible size of beautiful string Nikita can get.

Example
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.



题意:输入一个非空的只有 a和b 字符串,任意切除,使得字符串由三部分组成,1和3 部分 全部都是 a,2 部分全部都是b,(有的部分可以为空),让你求得切完的字符串

的最长长度为多少;

思路:任意删除字符,删除字符后的答案要和全部字符相关; 像这样一类的题一般都会用到 前缀和后缀。所以我们这道题也用前缀和后缀解决,以为1, 3 部分全部都是由a组成,2部分由 b组成,所以我们只需找每一个b之前之后有多少a就是,最后在枚举b的位置就行了,per[i]  + (j-i+1)  + suf[j]; j-i+1 是指i到j有多少个b;

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define Max 5500

char str[Max];
int pre[Max],suf[Max],pos[Max]; // 前缀,后缀,每个b的位置; 
int main()
{
	int i,j,n;
	while(~scanf("%s",str))
	{
		n = strlen(str);
		int num = 0;
		for(i=0;i<n;i++)
		{
			if(str[i]=='b')
			{
				pre[i] = i - num;  // 求前缀,每一个b前面有多少a; 
				pos[num++] = i;    // 记录b的位置; 
			}
		}
		int num1 = 0;
		for(i=n-1;i>=0;i--)
		{
			if(str[i]=='a')
				num1++;
			else if(str[i]=='b')
				suf[i] = num1; 	// 求后缀; 
		}
		if(num == 0)
		{
			printf("%d\n",n);
			continue;
		}
		int Ma = -INF;
		for(i=0;i<num;i++)   // 枚举每个b与b的区间 
		{
			for(j = i;j<num;j++)
			{
				int k = pos[i],t = pos[j]; 
				Ma = max(Ma,pre[k]+(j-i+1)+suf[t]);
			}
		}
		printf("%d\n",Ma);	
	}
	return 0;
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值