hdoj 2222

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

第一道 AC自动机。。。。。trie树的建立 和 AC自动机的查询,,可作模版。。。

解题思路:AC的应用。。。直接模版。。

 1 #include <iostream>
 2 #include<cstring>
 3 using namespace std;
 4 struct point {
 5    struct point *final;
 6    struct point *next[26];
 7     int count;
 8     point(){
 9         final =NULL;
10         count =0;
11         memset(next,NULL,sizeof(next));
12     }
13 }*q[500005];
14 
15 char str[55];
16 char tt[1000005];
17 int head, tail;
18 
19 void build_trie(char *str, point *root){
20     point *p = root;
21     int i=0,index;
22     while(str[i]){
23         index = str[i]-'a';
24         if(p->next[index]==NULL) p->next[index] = new point();
25         p = p->next[index];
26         i++;
27     }
28     p->count++;
29 }
30 
31 void get_final(point *root){
32     int i;
33     root->final = NULL;
34     q[head++] = root;
35     while(head!=tail){
36         point *temp = q[tail++];
37         point *p = NULL;
38         for(i=0;i<26;i++){
39             if(temp->next[i]!=NULL){
40                 if(temp==root) temp->next[i]->final=root;
41                 else{
42                     p = temp->final;
43                     while(p!=NULL){
44                         if(p->next[i]!=NULL){
45                             temp->next[i]->final = p->next[i];
46                             break;
47                         }
48                         p = p->final;
49                     }
50                     if(p==NULL) temp->next[i]->final=root;
51                 }
52                 q[head++] = temp->next[i];
53             }
54         }
55     }
56 }
57 
58 int requry(point *root){
59     int i =0,cnt=0,index;
60     //int len = strlen(t);
61     point *p =root;
62     while(tt[i]){
63         index = tt[i]-'a';
64         while(p->next[index]==NULL&&p!=root)  p= p->final;
65         p = p->next[index];
66         p=(p==NULL)? root:p;
67         point *temp =p;
68         while(temp!=root&&temp->count!=-1){
69             //cout<<"------------>"<<endl;
70             cnt += temp->count;
71             temp->count=-1;
72             temp = temp->final;
73         }
74         i++;
75     }
76 
77     return cnt;
78 }
79 int main()
80 {
81     int t;
82     cin>>t;
83     while(t--){
84         int n;
85         head =tail =0;
86         point *root = new point();
87         cin>>n;
88         while(n--){
89             cin>>str;
90             build_trie(str,root);
91         }
92         get_final(root);
93         cin>>tt;
94 
95         cout<<requry(root)<<endl;
96     }
97     return 0;
98 }
原文地址:https://www.cnblogs.com/Bang-cansee/p/3251028.html