题意:
对于给定的字符串,求每个子回文串中不同的字符个数之和。
思路:
回文树。
c
n
t
[
i
]
cnt[i]
cnt[i]表示节点
i
i
i 的回文串个数。
s
u
m
[
i
]
sum[i]
sum[i]表示节点
i
i
i 表示的回文串的不同字符个数。
在构造回文树的时候判断当前插入的字符 c c c 在其匹配位置 c u r cur cur 处是否出现过, 在继承 c u r cur cur的答案的基础上进行更新。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 3e5+5;
const int N = 27;
char s1[MAXN],s2[MAXN];
struct Palindromic_Tree {
int next[MAXN][N] ;//next指针,next指针和字典树类似,指向的串为当前串两端加上同一个字符构成
int fail[MAXN] ;//fail指针,失配后跳转到fail指针指向的节点
int cnt[MAXN] ; //表示节点i表示的本质不同的串的个数(建树时求出的不是完全的,最后count()函数跑一遍以后才是正确的)
int cnt2[MAXN][N];
int sum[MAXN];
int num[MAXN] ; //表示以节点i表示的最长回文串的最右端点为回文串结尾的回文串个数。
int len[MAXN] ;//len[i]表示节点i表示的回文串的长度
int S[MAXN] ;//存放添加的字符
int last ;//指向上一个字符所在的节点,方便下一次add
int n ;//字符数组指针
int p ;//节点指针
int newnode ( int l ) {//新建节点
for ( int i = 0 ; i < N ; ++ i ) next[p][i] = 0 ;
cnt[p] = 0 ;
sum[p] = 0;
num[p] = 0 ;
len[p] = l ;
return p ++ ;
}
void init () {//初始化
p = 0 ;
newnode ( 0 ) ; //奇
newnode ( -1 ) ; //偶
last = 0 ;
n = 0 ;
S[n] = -1 ;//开头放一个字符集中没有的字符,减少特判
fail[0] = 1 ;
}
int get_fail ( int x ) {//和KMP一样,失配后找一个尽量最长的
while ( S[n - len[x] - 1] != S[n] ) x = fail[x] ;
return x ;
}
void add ( int c ) {
c -= 'a' ;
S[++ n] = c ;
int cur = get_fail ( last ) ;//通过上一个回文串找这个回文串的匹配位置
if ( !next[cur][c] ) {//如果这个回文串没有出现过,说明出现了一个新的本质不同的回文串
int now = newnode ( len[cur] + 2 ) ;//新建节点
sum[now] += sum[cur];
//-------------------------------更新答案
for(int j = 0; j < 26; j++) if(cnt2[cur][j] == 1)cnt2[now][j] = cnt2[cur][j];
if(cnt2[now][c] == 0){
cnt2[now][c] = 1;
sum[now]++;
}
//-------------------------------------
fail[now] = next[get_fail ( fail[cur] )][c] ;//和AC自动机一样建立fail指针,以便失配后跳转
next[cur][c] = now ;
num[now] = num[fail[now]] + 1 ;
}
last = next[cur][c] ;
cnt[last] ++ ;
}
ll count () {
ll ans = 0;
for(int i = p-1; i >= 0; i--){
cnt[fail[i]] += cnt[i] ;
}
for(int i = 2; i <= p-1; i++)
ans += 1ll*(sum[i])*cnt[i];
return ans;
}
} pat1,pat2;
int main(){
scanf("%s",s1);
int len = strlen(s1);
pat1.init();
for(int i = 0; i < len; i++)
pat1.add(s1[i]);
ll ans = pat1.count();
printf("%lld\n",ans);
}