AC自动机模板题
下面是代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
string s,m;
int T,n,sz,ans;
int a[500001][27],q[500001];
int point[500001],danger[500001];
bool mark[500001];
void ins(){
int now=1,l=s.length();
for(int i=0;i<l;i++){
int t=s[i]-'a'+1;
if(!a[now][t]){
a[now][t]=++sz;
}
now=a[now][t];
}
danger[now]++;
}
void acmach(){
int t=0,w=1,now;
q[0]=1;point[1]=0;
while(t<w){
now=q[t++];
for(int i=1;i<=26;i++){
if(!a[now][i]){
continue;
}
int k=point[now];
while(!a[k][i]){
k=point[k];
}
point[a[now][i]]=a[k][i];
q[w++]=a[now][i];
}
}
}
void solve(){
int k=1,l=m.length()-1;
for(int i=0;i<l;i++){
mark[k]=1;
int t=m[i]-'a'+1;
while(!a[k][t]){
k=point[k];
}
k=a[k][t];
if(!mark[k]){
for(int j=k;j;j=point[j]){
ans+=danger[j];
danger[j]=0;
}
}
}
cout<<ans<<endl;
}
int main(){
cin>>T;
while(T--){
sz=1;ans=0;
cin>>n;
for(int i=1;i<=26;i++){
a[0][i]=1;
}
while(n--){
cin>>s;
ins();
}
acmach();
cin>>m;
solve();
for(int i=1;i<=sz;i++){
point[i]=danger[i]=mark[i]=0;
for(int j=1;j<=26;j++){
a[i][j]=0;
}
}
}
return 0;
}
/*
in:
1
5
she
he
say
shr
her
yasherhs
out:
3
*/