[HDOJ3065]病毒侵袭持续中

AC自动机入门题目~

View Code
1 #include <cstdio>
2 #include <cstring>
3
4 usingnamespace std;
5
6 constint NS =128;
7 constint MAXD =1024;
8 constint MAXDL =64;
9 constint MAXWL =2000005;
10 constint MAXN =65536;
11
12 struct TRIE
13 {
14 int lable;
15 int cnt;
16 TRIE * fail;
17 TRIE * son[NS];
18 TRIE()
19 {
20 lable =-1;
21 cnt =0;
22 fail = NULL;
23 for (int i =0;i < NS;i++)
24 son[i] = NULL;
25 }
26 };
27
28 TRIE * queue[MAXN];
29
30 int cnt[MAXD];
31
32 char word[MAXD][MAXDL];
33 char description[MAXWL];
34
35 void TrieInsert(char* _word,int id,TRIE * root)
36 {
37 char* key;
38 TRIE * tmp;
39
40 key = _word;
41 tmp = root;
42
43 while (*key)
44 {
45 int idx =*key++;
46 if (tmp->son[idx] == NULL) tmp->son[idx] =new TRIE();
47 tmp = tmp->son[idx];
48 }
49 tmp->cnt++;
50 tmp->lable = id;
51 }
52
53 void getFail(TRIE * root)
54 {
55 int qh =-1;
56 int qe =0;
57
58 queue[0] = root;
59 root->fail = NULL;
60
61 while (qh != qe)
62 {
63 qh++;
64
65 TRIE * tmp = queue[qh];
66
67 for (int i =0;i < NS;i++)
68 if (tmp->son[i])
69 {
70 if (tmp == root) tmp->son[i]->fail = root;
71 else
72 {
73 TRIE * p = tmp->fail;
74 while (p)
75 {
76 if (p->son[i])
77 {
78 tmp->son[i]->fail = p->son[i];
79 break;
80 }
81 p = p->fail;
82 }
83 if (p == NULL) tmp->son[i]->fail = root;
84 }
85
86 qe++;
87 queue[qe] = tmp->son[i];
88 }
89 }
90 }
91
92 void TrieFind(char* _word,TRIE * root)
93 {
94 char* key;
95 TRIE * tmp;
96
97 key = _word;
98 tmp = root;
99
100 while (*key)
101 {
102 int idx =*key++;
103
104 while (tmp->son[idx] == NULL && tmp != root) tmp = tmp->fail;
105 tmp = tmp->son[idx] == NULL ? root : tmp->son[idx];
106 TRIE * p = tmp;
107 while (p != root && p->lable !=-1)
108 {
109 cnt[p->lable] += p->cnt;
110 p = p->fail;
111 }
112 }
113 }
114
115 void TrieDelete(TRIE * root)
116 {
117 for (int i =0;i < NS;i++)
118 if (root->son[i])
119 TrieDelete(root->son[i]);
120 delete(root);
121 }
122
123 int main()
124 {
125 int dnum;
126
127 while (scanf("%d",&dnum) ==1)
128 {
129 memset(cnt,0,sizeof(cnt));
130 TRIE * root =new TRIE();
131
132 for (int i =0;i < dnum;i++)
133 {
134 scanf("%s",word[i]);
135 TrieInsert(word[i],i,root);
136 }
137
138 getFail(root);
139
140 scanf("%s",description);
141
142 TrieFind(description,root);
143
144 for (int i =0;i < dnum;i++)
145 if (cnt[i] !=0) printf("%s: %d\n",word[i],cnt[i]);
146
147 TrieDelete(root);
148 }
149 return0;
150 }
原文地址:https://www.cnblogs.com/debugcool/p/HDOJ3065.html