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

版权声明:本文为小时的枫原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaofeng187/article/details/79336042
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,每个字符串都可以为空。问最多能剩下几个字符。

扫描二维码关注公众号,回复: 5044213 查看本文章


做法:建立一个数组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);
}

猜你喜欢

转载自blog.csdn.net/xiaofeng187/article/details/79336042