Description
给出一个长度为n的只由a和b组成的字符串,问合法子串数量,一个子串是合法的当且仅当该子串把相邻的相同字母合并后是一个回文串
Input
输入一个串长不超过1e5的只有a和b组成的字符串
Output
输出长度分别为偶数和奇数的合法子串的数量
Sample Input
baab
Sample Output
2 4
Solution
因为一个子串在经过把相邻相同的字母合并后必然是一个ab相间的串,故只要该子串两端相同那么必然为一个合法子串,故只需要统计原串中位置为奇数或偶数的a和b的数量oa,ea,ob,eb,那么长度为偶数的合法子串数量就是选取一个在奇数位置一个在偶数位置的a或b,方案数oa*ea+ob*eb,长度为奇数的合法子串数量就是选取两个长度均为奇数或偶数的a或b,方案数C(oa,2)+C(ea,2)+C(ob,2)+C(eb,2)
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 111111
char s[maxn];
int main()
{
while(~scanf("%s",s+1))
{
int len=strlen(s+1),ea=0,oa=0,eb=0,ob=0;
for(int i=1;i<=len;i++)
if(s[i]=='a')
{
if(i&1)oa++;
else ea++;
}
else
{
if(i&1)ob++;
else eb++;
}
ll ans1=1ll*oa*ea+1ll*ob*eb;
ll ans2=len+1ll*(oa-1)*oa/2+1ll*(ea-1)*ea/2+1ll*(ob-1)*ob/2+1ll*(eb-1)*eb/2;
printf("%I64d %I64d\n",ans1,ans2);
}
return 0;
}