1. 程式人生 > >【BZOJ4566】找相同字符(後綴自動機)

【BZOJ4566】找相同字符(後綴自動機)

print tdi iostream extend 當前位置 字符 map 自動 code

【BZOJ4566】找相同字符(後綴自動機)

題面

BZOJ

題解

看到多串處理,\(SA\)就連起來
\(SAM???\)
單串建自動機
然後其他串匹配

對於一個串建完\(SAM\)
另一個串在\(SAM\)上匹配
記錄當前匹配的最大長度

匹配了當前位置的話,就能產生一定的貢獻
但是很顯然,沿著\(parent\)往上,所有點都能夠產生貢獻
所以匹配完再沿著\(parent\)做一遍類似\(dp\)的東西算貢獻

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath> #include<algorithm> #include<set> #include<map> #include<vector> #include<queue> using namespace std; #define MAX 220000 inline int read() { int x=0,t=1;char ch=getchar(); while((ch<'0'||ch>'9')&&ch!='-')ch=getchar(); if
(ch=='-')t=-1,ch=getchar(); while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar(); return x*t; } struct Node { int son[26]; int ff,len; }t[MAX<<1]; int last=1,tot=1; int size[MAX<<1]; long long ans; int f[MAX<<1],g[MAX<<1],a[MAX<<1
],c[MAX<<1]; char ch[MAX]; void extend(int c) { int p=last,np=++tot;last=np; t[np].len=t[p].len+1; while(p&&!t[p].son[c])t[p].son[c]=np,p=t[p].ff; if(!p)t[np].ff=1; else { int q=t[p].son[c]; if(t[q].len==t[p].len+1)t[np].ff=q; else { int nq=++tot; t[nq]=t[q]; t[nq].len=t[p].len+1; t[q].ff=t[np].ff=nq; while(p&&t[p].son[c]==q)t[p].son[c]=nq,p=t[p].ff; } } size[np]=1; } int main() { scanf("%s",ch+1); for(int i=1,l=strlen(ch+1);i<=l;++i)extend(ch[i]-97); for(int i=1;i<=tot;++i)c[t[i].len]++; for(int i=1;i<=tot;++i)c[i]+=c[i-1]; for(int i=1;i<=tot;++i)a[c[t[i].len]--]=i; for(int i=tot;i;--i)size[t[a[i]].ff]+=size[a[i]]; scanf("%s",ch+1); for(int i=1,l=strlen(ch+1),now=1,len=0;i<=l;++i) { int c=ch[i]-97; if(t[now].son[c])++len,now=t[now].son[c]; else { while(now&&!t[now].son[c])now=t[now].ff; if(!now)now=1,len=0; else len=t[now].len+1,now=t[now].son[c]; } ans+=1ll*size[now]*(len-t[t[now].ff].len); g[now]++; } for(int i=tot;i;--i)f[t[a[i]].ff]+=f[a[i]]+g[a[i]]; for(int i=1;i<=tot;++i)ans+=1ll*size[i]*f[i]*(t[i].len-t[t[i].ff].len); printf("%lld\n",ans); return 0; }

【BZOJ4566】找相同字符(後綴自動機)