Ac自动机模板题
#include <cstdio>
#include <cstring>
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
typedef long long ll;
using namespace std;
struct node{
node *fail;
node *next[26];
int cnt;
node(){
fail = NULL;
cnt = 0;
memset(next,NULL,sizeof(next));
}
}*q[500010];
char str[60];
char s[1000010];
void Insert(node *root){
node *p = root;
for(int i = 0;str[i];i++){
int num = str[i] - 'a';
if(p->next[num] == NULL) p->next[num] = new node();
p = p->next[num];
}
p->cnt++;
}
void Build_Ac(node *root){
int head = 0,tail = 0;
root->fail = NULL;
q[head++] = root;
while(head != tail){
node *temp = q[tail++];
node *p = NULL;
for(int i = 0;i < 26;i++){
if(temp->next[i] != NULL){
if(temp == root) temp->next[i]->fail = root;
else{
p = temp->fail;
while(p != NULL){
if(p->next[i] != NULL){
temp->next[i]->fail = p->next[i];
break;
}
p = p->fail;
}
if(p == NULL) temp ->next[i]->fail = root;
}
q[head++] = temp->next[i];
}
}
}
}
int Query(node *root){
int cnt = 0,l = strlen(s);
node *p = root;
for(int i = 0;s[i];i++){
int num = s[i] - 'a';
while(p->next[num] == NULL && p != root) p=p->fail;
p = p->next[num];
if(p == NULL) p = root;
else p = p;
node *temp = p;
while(temp != root && temp->cnt != -1 ){
cnt += temp->cnt;
temp->cnt = -1;
temp = temp->fail;
}
}
return cnt;
}
int main(){
int t;
while(~scanf("%d",&t)){
while(t--){
int n;
scanf("%d",&n);
node *root = new node();
for(int i = 0;i < n;i++){
scanf("%s",str);
Insert(root);
}
Build_Ac(root);
scanf("%s",s);
int num = Query(root);
printf("%d\n",num);
}
}
return 0;
}