P8406 [COCI2021-2022#6] Palindromi 题解
分析
这道题需要用到 PAM-回文自动机,不会的同学可以参考一下 OI-wiki。
有经验的可以发现,PAM 和 ACAM 一样,不支持低于
每次合并两个字符串,总是从小的字符串往大的字符串合并,这样的话我们需要处理如何对于一个字符串在后面添加字符处理出来自动机和在前面添加字符处理出来自动机。
根据回文的基本性质,也就是在回文树上,如果
因此,不管是从前面还是从后面添加字符,回文树的处理都是一样的。
我们只需要处理从第一个字符开始最长回文所代表的串在树上的节点
我们发现,如果在后面添加字符,除非整个串变成了回文串,那么
这两部分的时间复杂度是分开的,每一个部分的时间复杂度又都是线性(详细证明见 OI-wiki),所以加一个字符串的时间复杂度均摊下来也是线性的。
根据启发式合并的性质,一个字符最多被添加
代码
代码如下,仅供参考:
#include<bits/stdc++.h>
#define N 2000005
#define M 100005
using namespace std;
deque<char> s[M];
char ch;
int root_1[N],root0[N],n,i,j,fath[N],pam[N][2],tot,now1[N],now2[N],ans,len[N],fa[N],si[N],x,y,reals[N];
inline int gf(int x){return x==fa[x]?x:fa[x]=gf(fa[x]);}
inline void insert_front(int x,int root){
s[root].pop_front(),s[root].push_front((char)(x+'0')),s[root].push_front(' ');
while(s[root][1]!=s[root][len[now1[root]]+2]) now1[root]=fath[now1[root]];
if(!pam[now1[root]][x]) pam[now1[root]][x]=++tot,len[tot]=len[now1[root]]+2,reals[root]++;
int temp = pam[now1[root]][x];
now1[root]=fath[now1[root]];
while(now1[root]&&s[root][1]!=s[root][len[now1[root]]+2]) now1[root]=fath[now1[root]];
if(now1[root]) fath[temp]=pam[now1[root]][x];
else fath[temp]=root0[root];
now1[root]=temp;
if(len[temp]==s[root].size()-2) now2[root]=temp;
}
inline void insert_back(int x,int root){
int id = s[root].size()-1;
s[root].pop_back(),s[root].push_back((char)(x+'0')),s[root].push_back(' ');
while(s[root][id]!=s[root][id-len[now2[root]]-1]) now2[root]=fath[now2[root]];
if(!pam[now2[root]][x]) pam[now2[root]][x]=++tot,len[tot]=len[now2[root]]+2,reals[root]++;
int temp = pam[now2[root]][x];
now2[root]=fath[now2[root]];
while(now2[root]&&s[root][id]!=s[root][id-len[now2[root]]-1]) now2[root]=fath[now2[root]];
if(now2[root]) fath[temp]=pam[now2[root]][x];
else fath[temp]=root0[root];
now2[root]=temp;
if(len[temp]==s[root].size()-2) now1[root]=temp;
}
int main(){
ios::sync_with_stdio(false);
cin>>n;
for(i=1;i<=n;i++){
root_1[i]=++tot,root0[i]=++tot,fath[root0[i]]=root_1[i],len[root_1[i]]=-1;
now1[i]=now2[i]=root_1[i];
}
for(i=1;i<=n;i++) cin>>ch,s[i].push_back(' '),s[i].push_back(' '),si[i]=1,fa[i]=i,insert_back(ch-'0',i);
for(i=1;i<n;i++){
cin>>x>>y;
int f1 = gf(x),f2 = gf(y);
if(si[f1]<si[f2]){
fa[f1]=f2,si[f2]+=si[f1];
for(j=s[f1].size()-2;j>=1;j--) insert_front(s[f1][j]-'0',f2);
cout<<reals[f2]<<endl;
}
else{
fa[f2]=f1,si[f1]+=si[f2];
for(j=1;j<s[f2].size()-1;j++) insert_back(s[f2][j]-'0',f1);
cout<<reals[f1]<<endl;
}
}
return 0;
}