AC自动机模板

Posted zfdyf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AC自动机模板相关的知识,希望对你有一定的参考价值。

例题 hdu 6208 http://acm.hdu.edu.cn/showproblem.php?pid=6208

 1 const int maxn = 1e5;
 2 class ac_auto {
 3   private:
 4     struct node {
 5         int ctr;
 6         node *fail;
 7         node *next[26];
 8     };
 9     node nodes[maxn];
10     int top;
11     node *root;
12   public:
13     ac_auto() {
14         init();
15     }
16     inline void init() {
17         top = 0;
18         root = new_node();
19     }
20     inline node *new_node() {
21         nodes[top].fail = root;
22         nodes[top].ctr = 0;
23         for (int i = 0; i < 26; ++i) 
24             nodes[top].next[i] = root;
25         ++top;
26         return &nodes[top - 1];
27     }
28     void insert(const char *str) {
29         node *head = root;
30         for (; *str; ++str) {
31             int x = *str - a;
32             if (root == head->next[x])
33                 head->next[x] = new_node();
34             head = head->next[x];
35         }
36         ++head->ctr;
37     }
38     void build_fail() {
39         queue<node *> q;
40         for (int i = 0; i < 26; ++i)
41             if (root != root->next[i])
42                 q.push(root->next[i]);
43         while (!q.empty()) {
44             node *now = q.front();
45             q.pop();
46             for (int i = 0; i < 26; ++i) {
47                 if (root == now->next[i]) {
48                     now->next[i] = now->fail->next[i];
49                 } else {
50                     now->next[i]->fail = now->fail->next[i];
51                     q.push(now->next[i]);
52                 }
53             }
54         }
55     }
56     int query(const char *str) {
57         build_fail();
58         node *head = root;
59         int ret = 0;
60         for (; *str; ++str) {
61             int x = *str - a;
62             head = head->next[x];
63             node *tmp = head;
64             while (tmp != root) {
65                 if (-1 == tmp->ctr)
66                     break;
67                 ret += tmp->ctr;
68                 tmp->ctr = -1;
69                 tmp = tmp->fail;
70             }
71         }
72         return ret;
73     }
74 };

 

以上是关于AC自动机模板的主要内容,如果未能解决你的问题,请参考以下文章

HDU3247 Resource Archiver(AC自动机+BFS+DP)

模板AC自动机

HDU-2222-Keywords Search(AC自动机模板)

POJ3691DNA repair(AC自动机,DP)

HDU4057 Rescue the Rabbit(AC自动机+状压DP)

P3796 模板AC自动机(加强版) 题解(Aho-Corasick Automation)