CF 877B Nikita and string

简介: CF 877B Nikita and string

B. Nikita and string

time limit per test2 seconds

memory limit per test256 megabytes

inputstandard input

outputstandard 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

inputCopy

abba

outputCopy

4

inputCopy

bab

outputCopy

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.


题解:前缀和优化

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
char str[maxn];
int sum1[maxn], sum2[maxn];
/*
*/
int main() {
  scanf("%s", str + 1);
  int n = strlen(str + 1);
  for (int i = 1; i <= n; i++) {
    sum1[i] = sum1[i - 1];
    sum2[i] = sum2[i - 1];
    if (str[i] == 'a') sum1[i]++;
    if (str[i] == 'b') sum2[i]++;
  }
  int ans = 0;
  int mm = n;
  for (int i = 0; i <= n; i++) {
    mm = min(mm, sum2[i] - sum1[i]);
    ans = max(ans, sum2[i] - sum1[i] - mm);
  }
  cout << ans + sum1[n]<< endl;
  return 0;
}
相关文章
|
1月前
|
存储 C++ 容器
|
4月前
|
存储 算法 程序员
|
6月前
|
存储 缓存 安全
|
6月前
|
存储 编译器 C++
【C++】String -- 详解(下)
【C++】String -- 详解(下)
|
6月前
|
存储 JavaScript C语言
【C++】String -- 详解(上)
【C++】String -- 详解(上)
|
6月前
string的使用
string的使用
56 0
grep 查询 包含string1、string2和string3的行
您可以使用以下命令来查询包含多个字符串的行: ``` grep 'string1.*string2.*string3' filename ``` 其中,`string1`、`string2`和`string3`是您要过滤的字符串,`filename`是要查询的文件名。 上述命令使用正则表达式来匹配包含`string1`、`string2`和`string3`的行,并将结果输出。`.`表示匹配任意字符,`*`表示匹配前面的字符0次或多次。 您还可以使用`-E`选项来启用扩展正则表达式模式,以实现更复杂的匹配模式: ``` grep -E 'string1|string2|string3' f
194 0
|
Java 编译器
String那些事
String那些事
142 0
String那些事
|
Python JavaScript
1050. String Subtraction (20)
分析:很无奈,我想用python。实在是简单呀。 python: s1 = raw_input() s2 = raw_input() for e in s2: if e in s1: s1 = s1.
774 0
|
JavaScript Windows 移动开发