ac自动机模板

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 using namespace std;
 6 const int MAX = 26;
 7 struct node{
 8     node *fail;
 9     node *next[MAX];
10     int cnt;
11     node(){
12         fail = NULL;
13         cnt = 0;
14         memset(next, 0, sizeof(next));
15     }
16 }*q[500008];
17 char keyword[51];
18 char str[1000001];
19 int head, tail;
20 void insert(char *str, node *root){
21     node *p = root;
22     int i = 0, index;
23     while(str[i]){
24         index = str[i] - 'a';
25         if(p->next[index] == NULL) p->next[index] = new node();
26         p = p->next[index];
27         i++;
28     }
29     p->cnt++;
30 }
31 void build_ac_automation(node *root){
32     int i;
33     root->fail = NULL;
34     q[head++] = root;
35     while(head != tail){
36         node *temp = q[tail++];
37         node *p = NULL;
38         for(i = 0; i < 26; i++){
39             if(temp->next[i] != NULL){
40                 if(temp == root) temp->next[i]->fail = root;
41                 else {
42                     p = temp->fail;
43                     while(p != NULL){
44                         if(p->next[i] != NULL){
45                             temp->next[i]->fail = p->next[i];
46                             break;
47                         }
48                         p = p->fail;
49                     }
50                     if(p == NULL) temp->next[i]->fail = root;
51 
52                 }
53                 q[head++] = temp->next[i];
54             }
55         }
56     }
57 }
58 int query(node *root){
59     int i = 0, cnt = 0, index;
60     node *p = root;
61     while(str[i]){
62         index = str[i] - 'a';
63         while(p->next[index] == NULL && p != root) p = p->fail;
64         p = p->next[index];
65         p = (p == NULL)? root:p;
66         node *temp = p;
67         while(temp != root && temp->cnt != -1){
68             cnt += temp->cnt;
69             temp->cnt = -1;
70             temp = temp->fail;
71         }
72         i++;
73     }
74     return cnt;
75 }
76 int main()
77 {
78     int n, t;
79     scanf("%d", &t);
80     while(t--){
81         head = tail = 0;
82         node * root = new node();
83         scanf("%d", &n);
84         getchar();
85         while(n--){
86             gets(keyword);
87             insert(keyword,root);
88         }
89         build_ac_automation(root);
90         scanf("%s", str);
91 
92         printf("%d
", query(root));
93     }
94     //system("pause");
95     return 0;
96 }
原文地址:https://www.cnblogs.com/cshg/p/5952548.html