[HAOI2016]找相同字符 廣義後綴自動機_統計出現次數
阿新 • • 發佈:2019-01-20
spa char s 輸入輸出格式 長度 pen space ret std max
題目描述:
給定兩個字符串,求出在兩個字符串中各取出一個子串使得這兩個子串相同的方案數。兩個方案不同當且僅當這兩個子串中有一個位置不同。
輸入輸出格式
輸入格式:
兩行,兩個字符串 s1,s2,長度分別為n1,n2。1 <=n1, n2<= 200000,字符串中只有小寫字母
輸出格式:
輸出一個整數表示答案
題解:
對 $2$ 個字符串建立一個廣義後綴自動機.
實際上,廣義後綴自動機就是對多個字符串用一個自動機加以維護.
每加入完畢一個字符串時,將 $last$ 設為 $1$.
插入字符時,若 $ch[last][c]==0$,則與普通的插入無區別.
若 $ch[last][c]!=0$ ,我們就將這個情況考慮成普通插入中 $last$ 的祖先中有 $ch[q][c]!=0$ 的情況即可.
對每一種字符串都維護一個 $cnt$ 數組即可.
上述講的是廣義後綴自動機的建立.
在後綴自動機上,由於每個節點的 $right$ 的區間剛好是 $[right[f[p]],right[p]]$,點和點之間的計算時互不矛盾的.
每個點的貢獻為: $(dis[p]-dis[f[p]])*cnt[p][0]*cnt[p][1]$.
Code:
#include <cstdio> #include <algorithm> #include <cstring> #define setIO(s) freopen(s".in","r",stdin) #define maxn 1000000 #define N 30 #define ll long long using namespace std; char str[maxn]; int last=1,tot=1,n,m; int ch[maxn][N],cnt[maxn][2],f[maxn],dis[maxn],rk[maxn]; long long C[maxn],ans; void ins(int c){ int np=++tot,p=last; last=np; if(ch[p][c]){ int q=ch[p][c]; if(dis[q]==dis[p]+1) last=q; else { int nq=++tot; last=nq; f[nq]=f[q],dis[nq]=dis[p]+1; memcpy(ch[nq],ch[q],sizeof(ch[q])); f[q]=nq; while(p&&ch[p][c]==q) ch[p][c]=nq,p=f[p]; } } else{ dis[np]=dis[p]+1; while(p&&!ch[p][c]) ch[p][c]=np,p=f[p]; if(!p) f[np]=1; else{ int q=ch[p][c],nq; if(dis[q]==dis[p]+1) f[np]=q; else{ nq=++tot; dis[nq]=dis[p]+1; memcpy(ch[nq],ch[q],sizeof(ch[q])); f[nq]=f[q],f[q]=f[np]=nq; while(p&&ch[p][c]==q) ch[p][c]=nq,p=f[p]; } } } } int main(){ //setIO("input"); scanf("%s",str),n=strlen(str); for(int i=0;i<n;++i) ins(str[i]-‘a‘),cnt[last][0]=1; scanf("%s",str),m=strlen(str),last=1; for(int i=0;i<m;++i) ins(str[i]-‘a‘),cnt[last][1]=1; for(int i=1;i<=tot;++i) ++C[dis[i]]; for(int i=1;i<=tot;++i) C[i]+=C[i-1]; for(int i=1;i<=tot;++i) rk[C[dis[i]]--]=i; for(int i=tot;i>=1;--i) { int p=rk[i]; cnt[f[p]][0]+=cnt[p][0],cnt[f[p]][1]+=cnt[p][1]; ans+=(ll)(dis[p]-dis[f[p]])*cnt[p][0]*cnt[p][1]; } printf("%lld",ans); return 0; }
[HAOI2016]找相同字符 廣義後綴自動機_統計出現次數