ACM刷题之codeforce————Nikita and string

Nikita and string
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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
Copy
abba
output
4
input
Copy
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,第三个字符串只能有a,每个字符串都可以为空。问最多能剩下几个字符。


做法:建立一个数组pre来记录当前下标前面的a的个数,再建立一个数组nex来记录当前下标后面的a的个数。然后再两重循环遍历一段字符串内b的个数,计为sum。

当pre + sum + nex 最大时,就是剩下字符的最大值。


下面是ac代码:

#include<bits/stdc++.h>
using namespace std;
#define MID(x,y) ((x+y)>>1)
#define CLR(arr,val) memset(arr,val,sizeof(arr))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int N=5555;

char c[N];
int pre[N],nex[N];

int main()
{
	//freopen("f:/input.txt", "r", stdin);
	int i, j ,k, le, sum;
	scanf("%s", &c);
	le = strlen(c);
	CLR(pre, 0);
	CLR(nex, 0);
	sum = 0;
	for (i = 0 ; i < le; i++) {
		if (c[i] == 'a') ++sum;
		else pre[i] = sum;
	}
	sum = 0;
	for (i = le -1 ; i >= 0; i--) {
		if (c[i] == 'a') ++sum;
		else nex[i] = sum;
	}
	int maxn = -INF;
	for (i = 0; i < le; i++) {
		sum = 0;
		for (j = i; j < le; j++) {
			if (c[j] == 'b') {
				sum++;
				if (pre[i] + sum + nex[j] > maxn) maxn = pre[i] + sum + nex[j];
			}
			
		}
	}
	if (maxn == -INF) maxn = le;
	printf("%d\n", maxn);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值