[模板] 迴文樹/迴文自動機 && BZOJ3676:[Apio2014]迴文串
阿新 • • 發佈:2019-01-14
迴文樹/迴文自動機
放連結:
狀態數的線性證明
並沒有看懂上面的證明,所以自己腦補了一個...
引理: 每一個迴文串都是字串某個字首的最長迴文字尾.
證明. 考慮一個迴文串在字串中第一次出現的位置, 記為 \(S_{p_1 ... p_2}\), 它一定是 \(S_{1 ... p_2}\)的最長迴文字尾.
否則, 如果有 \(S_{p_3 ... p_2} (p_3<p_1)\) 也為迴文串, 那麼由於迴文, \(S_{p_3 ... p_3-p_2+p_1} = S_{p_1 ... p_2}\)
因而命題得證.
而每個點的最長迴文字尾是唯一的, 因此\(S\)最多隻有\(|S|\)個不同的迴文子串.
關於fail指標
fail指標指向的是一個節點代表的迴文串的最長迴文字尾.
在build時, 它也可以理解為以某個點為結尾的次長迴文字尾.
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; } }
例題
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; }