AC自动机(AC automation)

  字典树+KMP

  参考自: http://www.cppblog.com/mythit/archive/2009/04/21/80633.html

  

 1 const int MAXN = 26; //字典大小
 2 
 3 //定义结点
 4 struct node{
 5     node* fail;
 6     node* child[MAXN];
 7     int count;
 8     node(){
 9         fail = NULL;
10         count = 0;
11         memset(child, NULL, sizeof(child));
12     }
13 };
14 
15 //将词插入字典树
16 void insert(node* root, char* str){
17     node* p = root;
18     int i = 0;
19     while(str[i]){
20         int index = str[i] - 'a';
21         if(p->child[index] == NULL) p->child[index] = new node();
22         p = p->child[index];
23         ++i;
24     }
25     p->count++;
26 }
27 
28 //BFS构造失配指针/构建ACautomation
29 //由当前结点构造子结点失配指针
30 void build_acautomation(node* root){
31     queue<node*> q;
32     root->fail = NULL;
33     q.push(root);
34     while(!q.empty()){
35         node* temp = q.front();
36         node* p = NULL;
37         for(int i = 0; i < MAXN; ++i){
38             if(temp->child[i] != NULL){
39                 if(temp == root) temp->child[i]->fail = root;
40                 else{
41                     p = temp->fail;
42                     while(p != NULL){
43                         if(p->child[i] != NULL){
44                             temp->child[i]->fail = p->child[i];
45                             break;
46                         }
47                         p = p->fail;
48                     }
49                     if(p == NULL) temp->child[i]->fail = root;
50                 }
51                 q.push(temp->child[i]);
52             }
53         }
54     }
55 }
56 
57 //ACautomation匹配
58 //计算当前进行匹配的字符串及其后缀子串的个数
59 //count因题而异
60 int query(node* root){
61     int i = 0, cnt = 0, index;
62     node* p = root;
63     while(str[i]){
64         index = str[i]-'a';
65         while(p->child[index] == NULL && p != root) p = p->fail;
66         p = p->child[index];
67         p = (p == NULL ? root : p);
68         node* temp = p;
69         while(temp != root && temp->count != -1){
70             cnt += temp->count;
71             temp->count = -1;
72             temp = temp->fail;
73         }
74         ++i;
75     }
76     return cnt;
77 }

 

  继续学习..........准备做题(VJ kuangbin AC自动机专题)

 

转载于:https://www.cnblogs.com/book-book/p/5357669.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值