duel CF 上刷到的,晚了 5s 被薄纱了 /kk。
题目给定一个字符串只含 ,求分别有多少长度为偶 / 奇的子串为“好回文串”。
字符串 ,为 “好回文串” 当且仅当合并连续相同字符后为回文串。
比较重要的就是要想到一个字符串为好回文串当且仅当其中 的个数为偶数,证明不难。
然后就有 的做法了。
容易发现可以直接做 个数的前缀和,记 到第 个字符的前缀和,从 1 遍历到 ,假如当前遍历到第 位,记 为所有 的个数,然后第 位会更新答案为 ( 为长度为偶数的答案, 为长度为奇数的答案),然后 ,对于长度为 1 的子串特殊处理即最后 。
时间复杂度 。
#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
#define int long long
#define db double
#define endl '\n'
#define lowbit(x) x&-x
#define intz(x,a) memset(x,a,sizeof(x));
const int N=1e5+5;
char s[N];int cnt[N],ct[N][2];
signed main(){cin>>(s+1);int n=strlen(s+1),ans0=0,ans1=0;
for(int i=2;i<=n;i++)if(s[i]^s[i-1])++cnt[i];
for(int i=2;i<=n;i++)cnt[i]+=cnt[i-1];
for(int i=1;i<=n;i++){
ans0+=ct[cnt[i]%2][!(i%2)],ans1+=ct[cnt[i]%2][i%2];
++ct[cnt[i]%2][i%2];
}cout<<ans0<<' '<<n+ans1;
return 0;
}