一、不挣扎了,直接背。
首先,回文树有何功能?
假设我们有一个串S,S下标从0开始,则回文树能做到如下几点:
1.求串S前缀0~i内本质不同回文串的个数(两个串长度不同或者长度相同且至少有一个字符不同便是本质不同)
2.求串S内每一个本质不同回文串出现的次数
3.求串S内回文串的个数(其实就是1和2结合起来)
4.求以下标i结尾的回文串的个数
这里有个很巧妙的地方,0作为偶数串的根,1作为奇数串的根。
板子:
设字符集大小为m,母串长度为n,则空间复杂度为O(nm),时间复杂度为O(nlogm)
p:不同回文串的种类,本质不同串的个数;
last:指向 新添加一个字母后所形成的最长回文串(以新添加的字母为右端点)表示的 节点
const int maxn = 100005 ;
const int N = 26 ;
struct Palindromic_Tree {
int next[maxn][N] ;//这是一棵字典树。
int fail[maxn] ;
int cnt[maxn] ; //表示节点i表示的本质不同的串出现的次数
//(建树时求出的不是完全的,最后count()函数跑一遍以后才是正确的)
int num[maxn] ; //表示以节点i表示的最长回文串的 最右端点 为回文串结尾的回文串个数
int len[maxn] ;//len[i]表示节点i表示的回文串的长度(一个节点表示一个回文串)
int S[maxn] ;
int last ;//指向新添加一个字母后所形成的最长回文串表示的节点。
int n ;//表示添加的字符个数。
int p ;//表示添加的节点个数。
int newnode ( int l )
{
for ( int i = 0 ; i < N ; ++ i ) next[p][i] = 0 ;
cnt[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 )
{
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 ) ;
fail[now] = next[get_fail ( fail[cur] )][c] ;
next[cur][c] = now ;
num[now] = num[fail[now]] + 1 ;
}
last = next[cur][c] ;
cnt[last] ++ ;
}
void count ()
{
for ( int i = p - 1 ; i >= 0 ; -- i ) cnt[fail[i]] += cnt[i] ;
}
} ;
二、例题:
(一)
Palindromes and Super Abilities URAL - 1960 :
After solving seven problems on Timus Online Judge with a word “palindrome” in the problem name, Misha has got an unusual ability. Now, when he reads a word, he can mentally count the number of unique nonempty substrings of this word that are palindromes.
Dima wants to test Misha’s new ability. He adds letters s 1, …, s n to a word, letter by letter, and after every letter asks Misha, how many different nonempty palindromes current word contains as substrings. Which n numbers will Misha say, if he will never be wrong?
Input
The only line of input contains the string s 1… s n, where s i are small English letters (1 ≤ n ≤ 10 5).
Output
Output n numbers separated by whitespaces, i-th of these numbers must be the number of different nonempty substrings of prefix s 1… s i that are palindromes.
Example
input
aba
output
1 2 3
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#define ll long long
using namespace std;
const int maxn = 100005 ;
const int N = 26 ;
struct Palindromic_Tree {
int next[maxn][N] ;
int fail[maxn] ;
int cnt[maxn] ;
int num[maxn] ;
int len[maxn] ;
int S[maxn] ;
int last ;
int n ;
int p ;
int newnode ( int l ) {
for ( int i = 0 ; i < N ; ++ i ) next[p][i] = 0 ;
cnt[p] = 0 ;
num[p]