时间限制: 1 Sec 内存限制: 128 MB
提交: 226 解决: 42
[提交] [状态] [命题人:admin]
题目描述
You are given a string s consisting of A, B and C.
Snuke wants to perform the following operation on s as many times as possible:
Choose a contiguous substring of s that reads ABC and replace it with BCA.
Find the maximum possible number of operations.
Constraints
1≤|s|≤200000
Each character of s is A, B and C.
输入
Input is given from Standard Input in the following format:
S
输出
Find the maximum possible number of operations.
样例输入
复制样例数据
ABCABC
样例输出
3
提示
You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.
看到题就知道,肯定和紧接着'BC'之前'A'的个数有关。我们分析一下样例,第一个'BC'之前有1个'A',ans+1;操作后变为'BCAABC',第二个'BC'之前有两个紧挨着的2个'A',ans+2;所以答案为3。多写几种情况,就可以发现答案就是'BC'之前有用的'A'的个数之和。一定要注意有用的'A'是指经过操作之后,可以和'BC'连在一起的'A',并且'BC'之后只能有'A'、'BC',不能有单个的'B'或'C'。再举几个例子。
1、“ABCABCABC”
第一个'BC'之前有1个'A',第二个'BC'有2个有用的'A',第三个'BC'有3个有用的'A',答案就是6。
2、“AABCBABC”
这个串可以分为两部分计算,显然串被中间的一个'B'断开了。'AABC'部分贡献为2,'ABC'部分贡献为1,所以答案为3。
代码实现就是统计每个'BC'之前有用的'A'的个数,求和即可。
(PS:代码能力还是太差,思路出来之后,写了半天。。)
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 2e5+10;
char s[N];
int main(void)
{
int n,i,cnt;
ll ans=0;
scanf("%s",s+1);
n=strlen(s+1);
i=1;
cnt=0;//统计有用的'A'的个数
while(i<=n)
{
if(s[i]=='A')
{
cnt=1;
int j=i+1;
while(j<=n)
{
if(s[j]=='B')
{
if(j+1<=n)
{
if(s[j+1]=='C')
{
//cout<<j+1<<endl;
ans+=cnt;
j+=2;
}
else if(s[j+1]=='A')
{
cnt=0;
i=j+1;
break;
}
else
{
cnt=0;
i=j+2;
break;
}
}
else
{
i=n+1;
break;
}
}
else if(s[j]=='A')
{
cnt++;
j++;
}
else
{
cnt=0;
i=j+1;
break;
}
}
if(j>n)
break;
}
else
i++;
// i++;
}
printf("%lld\n",ans);
return 0;
}
/*
AABCCABCABCABC
*/