【AC自动机】单词

传送门:CodeVS2542


思路:AC自动机模板题,然而每次跳Fail边可能会TLE,所以节点上存一个类似于前缀和的东西


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define LL long long
LL n,xb,cnt,tmp,sum[1000030],ans[1000030],q[1000030],pos[1000030];
char s[205][100030];
struct AC{LL c[30],fail,data,last;}T[1000030];
void calc(LL x){while (x){ans[x]+=T[x].data; x=T[x].last;}}
int main(){
scanf("%lld",&n);
for (LL i=1;i<=n;i++){
scanf("%s",s[i]+1); LL len=strlen(s[i]+1);
xb=0;
for (LL j=1;j<=len;j++){
LL num=s[i][j]-'a'+1;
if (T[xb].c[num]) xb=T[xb].c[num];
else{T[xb].c[num]=++cnt; xb=cnt;}
}
T[xb].data++; pos[i]=xb; sum[xb]++;
}
T[0].fail=-1; LL tt=0,ww=1; q[1]=0;
while (tt<ww){
LL xb=q[++tt];
for (LL i=1;i<=26;i++){
LL &u=T[xb].c[i],v=T[xb].fail;
if (v!=-1) v=T[v].c[i]; else v=0;
if (!u){u=v; continue;}
T[u].fail=v; if (T[v].data) T[u].last=v; else T[u].last=T[v].last; q[++ww]=u;
}
}
for (LL i=1;i<=n;i++){
LL len=strlen(s[i]+1); xb=0;
for (LL j=1;j<=len;j++){
LL num=s[i][j]-'a'+1;
xb=T[xb].c[num]; calc(xb);
}
}
for (LL i=1;i<=n;i++) printf("%lld\n",ans[pos[i]]/sum[pos[i]]);
return 0;
}