AB-string CodeForces - 1238D
题意
如果一个字符串的每个字母,属于至少一个(长度大于1)的回文串,则称这个字符串为good。给出仅由AB组成的字符串,求出good子串数量。
思路
由于字符串只能由AB两种字符构成,如若其不为good
串,其结构应为
AAA...ABBBB...BAAB...BBBBA...AAA
AAA...AB \\
BBB...BA\\
AB...BBB\\
BA...AAA\\
AAA...ABBBB...BAAB...BBBBA...AAA
所以可以通过总的子串数n(n−1)2\frac{n(n-1)}{2}2n(n−1)减去不为good串的子串数量。
注意
使用longlong,否则的溢出
AC代码
#include <iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#define ll long long
using namespace std;
int main()
{
ll n;
int f=0;
ll ans=0;
string s;
cin>>n>>s;
ans= n*(n-1)/2;
for(int i=1;i<n;i++)
{
if(s[i]!=s[i-1])
{
ans-=i-f;
f=i;
}
else if(f)
ans--;
}
printf("%lld",ans);
return 0;
}
CodeForces-1238D题解
本文解析了CodeForces-1238D题目——AB-string问题,该题要求找出由AB组成的字符串中所有好的子串数量。通过对字符串结构的观察,提出了一种快速计算的方法,并给出了完整的AC代码。
295

被折叠的 条评论
为什么被折叠?



