HDOJ 2222 AC自动机

链接:

http://acm.hdu.edu.cn/showproblem.php?pid=2222

代码:

 31 string s;
 32 
 33 struct node {
 34     node *fail;
 35     node *next[26];
 36     int count;
 37     node() {
 38         fail = NULL;
 39         count = 0;
 40         rep(i, 0, 26) next[i] = NULL;
 41     }
 42 }*root;
 43 queue<node*> que;
 44 
 45 void insert(string s) {
 46     node *p = root;
 47     int len = s.length();
 48     rep(i, 0, len) {
 49         int temp = s[i] - 'a';
 50         if (p->next[temp] == NULL) p->next[temp] = new node();
 51         p = p->next[temp];
 52     }
 53     p->count++;
 54 }
 55 
 56 void build_ac() {
 57     que.push(root);
 58     while (!que.empty()) {
 59         node *p = que.front(); que.pop();    
 60         rep(i, 0, 26) if (p->next[i] != NULL) {
 61             if (p == root) p->next[i]->fail = root;
 62             else {
 63                 node *temp = p->fail;
 64                 while (temp != NULL) {
 65                     if (temp->next[i] != NULL) {
 66                         p->next[i]->fail = temp->next[i];
 67                         break;
 68                     }
 69                     temp = temp->fail;
 70                 }
 71                 if (temp == NULL) p->next[i]->fail = root;
 72             }
 73             que.push(p->next[i]);
 74         }
 75     }
 76 }
 77 
 78 int query() {
 79     int res = 0;
 80     node *p = root;
 81     int len = s.length();
 82     rep(i, 0, len) {
 83         int index = s[i] - 'a';
 84         while (p->next[index] == NULL && p != root) p = p->fail;
 85         p = p->next[index];
 86         if (p == NULL) p = root;
 87         node *temp = p;
 88         while (temp != root && temp->count != -1) {
 89             res += temp->count;
 90             temp->count = -1;
 91             temp = temp->fail;
 92         }
 93     }
 94     return res;
 95 }
 96 
 97 int main() {
 98     ios::sync_with_stdio(false), cin.tie(0);
 99     int T;
100     cin >> T;
101     while (T--) {
102         root = new node();
103         int n;
104         cin >> n;
105         while (n--) {
106             cin >> s;
107             insert(s);
108         }
109         build_ac();
110         cin >> s;
111         cout << query() << endl;
112     }
113     return 0;
114 }
原文地址:https://www.cnblogs.com/baocong/p/6792950.html