[TJOI2013]單詞 [AC自動機]
阿新 • • 發佈:2018-12-15
#include<bits/stdc++.h> #define N 1000050 using namespace std; int pos[N],siz[N],fail[N]; int ch[N][26],n,tot,ret,id[N]; void Insert(int id,string s){ int len = s.length() , now = 0; for(int i=0;i<len;i++){ int x = s[i] - 'a'; if(!ch[now][x]) ch[now][x] = ++tot; now = ch[now][x]; siz[now]++; } pos[id] = now; } void build(){ queue<int> q; for(int i=0;i<26;i++) if(ch[0][i]) q.push(ch[0][i]) , id[++ret] = ch[0][i]; while(!q.empty()){ int x = q.front(); q.pop(); for(int i=0;i<26;i++) if(ch[x][i]){ int j = fail[x]; while(j&&!ch[j][i]) j=fail[j]; if(ch[j][i]) fail[ch[x][i]] = ch[j][i]; q.push(ch[x][i]); id[++ret] = ch[x][i]; } } } void Solve(){ for(int i=ret;i>=1;i--) siz[fail[id[i]]] += siz[id[i]]; for(int i=1;i<=n;i++) printf("%d\n",siz[pos[i]]); } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++){ string s; cin>>s; Insert(i,s); } build(); Solve(); return 0; }