题目大意:
给你一个字符串,你要在字符串中寻找所有的回文串,一个回文串的价值是它包含的不同字符的个数,问你最后所有的回文串的价值总和是多少?
思路:
首先需要找出所有的回文串,不难想到回文树,用回文树处理字符串后,每个节点的cnt包含对应节点的回文串的个数,我们只需要知道对于每个回文串,他的位置在哪里。
这个操作也很常见,可以在回文树中标记每个回文串的终止位置pos,回文树中记录了回文串的长度,所以这个节点表示的回文串,就是pos[i]-len[i]+1到pos[i]。
然后我们要在原串中统计这个区间内不同字符的个数,那么就变成了一个常见的主席树求区间不同数的个数的问题,可以在log的时间内快速解决。
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define ll long long
const int N=5e5+10;
char s[N];
int n,last,len[N],fail[N],cnt[N],p,nex[N][26];
int tot, root[N], a[N], pre[N], l, r, k, ans;
int s_len[N], pos[N];
struct node{int l, r, sum;} T[N*25];
void update(int l,int r,int &now, int pre, int pos, int c)
{
T[++tot] = T[pre], T[tot].sum += c, now = tot;
if(l == r) return;
int mid = (l + r) >> 1;
if(mid >= pos) update(l, mid, T[now].l, T[pre].l, pos, c);
else update(mid + 1, r, T[now].r, T[pre].r, pos, c);
}
int query(int l, int r, int rt, int L, int R)
{
if(L <= l && r <= R) return T[rt].sum;
int mid = (l + r) / 2;
int res = 0;
if(mid >= L) res += query(l, mid, T[rt].l, L, R);
if(mid < R) res += query(mid+1, r, T[rt].r, L, R);
return res;
}
int main()
{
scanf("%s",s+1); n=strlen(s+1);
for(int i = 1; i <= n; i++) a[i] = s[i] - 'a' + 1;
for(int i = 1; i <= n; i++)
{
update(1, n, root[i], root[i-1], i, 1);
if(pre[a[i]]) update(1, n, root[i], root[i], pre[a[i]], -1);
pre[a[i]] = i;
}
p = 1; len[1] = -1; fail[0] = 1; fail[1] = -1;
for(int i = 1; i <= n; i++)
{
while(s[i-len[last]-1] != s[i])
last = fail[last];
int &g = nex[last][s[i]-'a'];
if(!g)
{
g = ++p, len[g] = len[last] + 2;
if(len[g] > 1) pos[p] = i; //记录回文串的下标
int k = fail[last];
while (k != -1 && s[i-len[k]-1] != s[i]) k = fail[k];
if(k == -1) fail[g] = 0;
else fail[g] = nex[k][s[i]-'a'];
}
cnt[g]++;
last = g;
}
for(int i = p; i >= 0; i--) cnt[fail[i]] += cnt[i];
ll ans = n;
for(int i = 2; i <= p; i++)
if(len[i] > 1) ans += query(1, n, root[pos[i]], pos[i] - len[i] + 1, pos[i]) * cnt[i];
printf("%lld\n", ans);
}