# [模板] 回文树/回文自动机 && BZOJ3676:[Apio2014]回文串

## 回文树/回文自动机

### 关于fail指针

fail指针指向的是一个节点代表的回文串的最长回文后缀.

## Code

const int ssz=300050;
ll n;
char s[ssz];

struct te{int l,fail,cnt,ch[27];}tree[ssz]{{0,1},{-1,1}};
int pt=1,rt0=0,rt1=1;
#define ch(p,c) tree[p].ch[c]
#define fail(p) tree[p].fail
int newnd(){return ++pt;}

int getfail(int p,int i){
while(s[i-1-tree[p].l]!=s[i])p=fail(p);
return p;
}
void build(){
int p,q,last=0;
rep(i,1,n){
p=getfail(last,i);
if(ch(p,s[i])==0){
q=newnd();
tree[q].l=tree[p].l+2,fail(q)=ch(getfail(fail(p),i),s[i]);
ch(p,s[i])=q;
}
last=ch(p,s[i]);
++tree[last].cnt;
}
}


## 应用

dfs即可.

### 求字符串出现次数

cnt[p] 即为回文串 $p$ 出现次数.

### 每个节点长度 $\le \frac {len}2$ 的回文后缀

struct tnd{int l,fi,ch[csz],tr;}tree[ssz];
#define ch(p,c) tree[p].ch[c]
#define fail(p) tree[p].fi
#define trl(p) tree[p].l
#define trtr(p) tree[p].tr
int rt0=0,rt1=1,pt=1;
int getfail(int p,int i){
while(s[i-1-trl(p)]!=s[i])p=fail(p);
return p;
}
void build(){
int p,q,last=0;
rep(i,1,n){
p=getfail(last,i);
if(ch(p,s[i])==0){
q=++pt;
trl(q)=trl(p)+2,fail(q)=ch(getfail(fail(p),i),s[i]);
//get tr(p) start
if(trl(q)<=1)trtr(q)=fail(q);
else{
int z=trtr(p);
while(s[i-1-trl(z)]!=s[i]||(trl(z)+2)*2>trl(q))z=fail(z);
trtr(q)=ch(z,s[i]);
}
//end
ch(p,s[i])=q;
}
last=ch(p,s[i]);
}
}


## 例题

BZOJ3676:[Apio2014]回文串

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
#define rep(i,l,r) for(register int i=(l);i<=(r);++i)
#define repdo(i,l,r) for(register int i=(l);i>=(r);--i)
#define il inline
typedef double db;
typedef long long ll;

//---------------------------------------
const int ssz=300050;
ll n,ans=0;
char s[ssz];

struct te{int l,fail,cnt,ch[27];}tree[ssz]{{0,1},{-1,1}};
int pt=1,rt0=0,rt1=1;
#define ch(p,c) tree[p].ch[c]
#define fail(p) tree[p].fail
int newnd(){return ++pt;}

int getfail(int p,int i){
while(s[i-1-tree[p].l]!=s[i])p=fail(p);
return p;
}
void build(){
int p,q,last=0;
rep(i,1,n){
p=getfail(last,i);
if(ch(p,s[i])==0){
q=newnd();
tree[q].l=tree[p].l+2,fail(q)=ch(getfail(fail(p),i),s[i]);
ch(p,s[i])=q;
}
last=ch(p,s[i]);
++tree[last].cnt;
}
}

int main(){
ios::sync_with_stdio(0),cin.tie(0);
cin>>(s+1);
n=strlen(s+1);
rep(i,1,n)s[i]-='a'-1;
build();
repdo(i,pt,2){
tree[fail(i)].cnt+=tree[i].cnt;
ans=max(ans,(ll)tree[i].cnt*tree[i].l);
}
cout<<ans<<'\n';
return 0;
}

posted @ 2019-01-14 16:54  Ubospica  阅读(197)  评论(0编辑  收藏  举报