您的位置:首页 > 其它

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

2018-02-18 23:31 337 查看
Nikita and stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne 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?InputThe first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".OutputPrint a single integer — the maximum possible size of beautiful string Nikita can get.ExamplesinputCopy
abba
output
4
inputCopy
bab
output
2
NoteIt 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
;
int pre
,nex
;

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: