AC自动机入门题,直接敲就行。
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<iostream>
#define sig 26
#define maxn 500005
using namespace std;
struct pi{
pi *fail;
pi *next[sig];
int val;
int cover;
pi(){
fail=NULL;
val=0;
cover=0;
memset(next,NULL,sizeof(next));
}
};
pi *head,*temp;
queue<pi *>q;
char c[10015][55];
char d[1000015];
void get_trie(int n){
int i,j,m;
head=new pi();
for(i=0;i<n;i++){
m=(int)strlen(c[i]);
temp=head;
for(j=0;j<m;j++){
if(temp->next[c[i][j]-'a']!=NULL) temp=temp->next[c[i][j]-'a'];
else{
temp->next[c[i][j]-'a']=new pi();
temp=temp->next[c[i][j]-'a'];
}
}
temp->val++;
}
}
void get_fail(void){
int i,j;
pi *fa;
while(!q.empty()) q.pop();
for(i=0;i<sig;i++){
if(head->next[i]!=NULL) (head->next[i])->fail=head;
}
for(i=0;i<sig;i++){
if(head->next[i]==NULL) continue;
q.push(head->next[i]);
while(!q.empty()){
temp=q.front();
q.pop();
for(j=0;j<sig;j++){
if(temp->next[j]==NULL) continue;
fa=temp->fail;
while(fa!=NULL&&fa->next[j]==NULL) fa=fa->fail;
if(fa!=NULL) fa=fa->next[j];
else fa=head;
(temp->next[j])->fail=fa;
q.push(temp->next[j]);
}
}
}
}
int find(char *T){
int i,cnt=0;
pi *j;
int n;
n=(int)strlen(T);
j=head;
for(i=0;i<n;i++){
while(j!=NULL&&j->next[T[i]-'a']==NULL) j=j->fail;
if(j!=NULL) j=j->next[T[i]-'a'];
else j=head;
temp=j;
while(temp!=NULL&&temp->cover!=-1){
cnt+=temp->val;
temp->cover=-1;
temp=temp->fail;
}
}
return cnt;
}
int main()
{
int i,n;
int t;
cin>>t;
while(t--){
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%s",c[i]);
scanf("%s",d);
get_trie(n);
get_fail();
printf("%d\n",find(d));
q.push(head);
while(!q.empty()){
temp=q.front();
q.pop();
for(i=0;i<sig;i++) if(temp->next[i]!=NULL) q.push(temp->next[i]);
free(temp);
}
}
}