hdu2222

链接:hdu2222

题解

  • ac自动机模板
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
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<queue>
#include<algorithm>
#define rint register int
#define rep(i,x,y) for(rint i=x;i<=y;++i)
#define repd(i,x,y) for(rint i=x;i>=y;--i)
#define ll long long
using namespace std;
const int N=1e6+7;
int tr[N][26],End[N],fail[N],cnt,ans,T,n;
char a[N];
inline void build(char *str,int len){
int now=0;
rep(i,1,len){
int k=str[i]-'a';
if(!tr[now][k])tr[now][k]=++cnt;
now=tr[now][k];
}
End[now]++;
}
inline void pre(){
queue<int> q;
q.push(0);
fail[0]=-1;
while(!q.empty()){
int k=q.front();q.pop();
rep(i,0,25)if(tr[k][i]){
int son=tr[k][i],p=fail[k];
while(p>=0&&!tr[p][i])p=fail[p];
fail[son]=p>=0?tr[p][i]:0;
q.push(son);
}
}
}
inline void query(char *str,int len){
int now=0;
rep(i,1,len){
int p=now,k=str[i]-'a';
while(p>=0&&!tr[p][k])p=fail[p];
now=p>=0?tr[p][k]:0;
int tmp=now;
while(tmp){if(End[tmp]>=0)ans+=End[tmp],End[tmp]=-1;else break;tmp=fail[tmp];}
}
}
int main(){
scanf("%d",&T);
while(T--){
memset(tr,0,sizeof(tr));
memset(fail,0,sizeof(fail));
memset(End,0,sizeof(End));
scanf("%d",&n);ans=cnt=0;
rep(i,1,n){scanf("%s",a+1);
build(a,strlen(a+1));}
pre();
scanf("%s",a+1);
query(a,strlen(a+1));
printf("%d\n",ans);
}
return 0;
}