看完了《训练指南》AC自动机这部分,找个入门题练练手。
题意比较简单,就是给N个串(可能有相同的,得重复计),然后给一个文本,统计N个串中有多少个在文本中出现。
http://acm.hdu.edu.cn/showproblem.php?pid=2222
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char s[1000010];
int t, n, ans;
struct ACAuto{
int ch[1000010][26];
int val[1000010];
int f[1000010], last[1000010];
int sz;
void init(){
sz=1;
memset(ch[0],0,sizeof(ch[0]));
}
int idx(char ch){
return ch-'a';
}
void insert(){
int len=strlen(s);
int u=0;
int c;
for(int i=0; i<len; i++){
c=idx(s[i]);
if(!ch[u][c]){
val[sz]=0;
memset(ch[sz],0,sizeof(ch[sz]));
ch[u][c]=sz++;
}
u=ch[u][c];
}
val[u]++;
}
void getfail(){
queue<int> Q;
f[0]=0;
for(int c=0; c<26; c++){
int u=ch[0][c];
if(u){
f[u]=0; Q.push(u); last[u]=0;
}
}
while(!Q.empty()){
int r=Q.front(); Q.pop();
for(int c=0; c<26; c++){
int u=ch[r][c];
if(!u) continue;
Q.push(u);
int v=f[r];
while(v&&!ch[v][c]) v=f[v];
f[u]=ch[v][c];
last[u]=val[f[u]]?f[u]:last[f[u]];
}
}
}
void cal(int x){
while(x){
ans+=val[x];
val[x]=0;
x=last[x];
}
}
void find(){
int len=strlen(s);
int j=0;
for(int i=0; i<len; i++){
int c=idx(s[i]);
while(j && !ch[j][c]) j=f[j];
j=ch[j][c];
cal(j);
}
printf("%d\n",ans);
}
}ac;
int main(){
scanf("%d", &t);
while(t--){
scanf("%d", &n);
ac.init();
while(n--){
scanf("%s", s);
ac.insert();
}
ac.getfail();
scanf("%s", s);
ans=0;
ac.find();
}
return 0;
}