HDU 2896 AC自动机

 

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2896

典型的模板题,用了2个模板,有一个就是不过,卡了我快一天了TvT,超级郁闷,改用另一个模板就ac了。两个模板的差别就是队列一个用STL,一个数组自己模拟。结果STL的过了,数组的就是过不了~~纠结郁闷,下次遇到还是果断STL算了~~

  1 #include <stdio.h>
2 #include <string.h>
3 #include <math.h>
4 #include <vector>
5 #include <algorithm>
6 #include <queue>
7 using namespace std;
8
9 #define KIND 128
10 #define M 10010
11
12 struct node
13 {
14 node *fail;
15 node *next[KIND];
16 int id;
17 node ()
18 {
19 fail = NULL;
20 id = 0;
21 memset(next, 0, sizeof(next));
22 }
23 };
24
25 char ch[M];
26 queue<node *> q;
27 vector<int> g;
28 int vis[M];
29 void insert(node *&root, char *ch, int id)
30 {
31 node *p = root;
32 int i = 0, t;
33 while(ch[i])
34 {
35 t = ch[i] - 31;
36 if(!p->next[t]) p->next[t] = new node();
37 p = p->next[t];
38 i++;
39 }
40 p->id = id;
41 }
42
43 void AC(node *&root)
44 {
45 q.push(root);
46 while(!q.empty())
47 {
48 node *p = NULL;
49 node *t = q.front();
50 q.pop();
51 for(int i = 0; i < KIND; i++)
52 {
53 if(t->next[i])
54 {
55 p = t->fail;
56 while(p)
57 {
58 if(p->next[i])
59 {
60 t->next[i]->fail = p->next[i];
61 break;
62 }
63 p = p->fail;
64 }
65 if(!p) t->next[i]->fail = root;
66 q.push(t->next[i]);
67 }
68 }
69 }
70 }
71
72 bool query(node *&root, char *ch,int count)
73 {
74 g.clear();
75 int i = 0, t, top = 0;
76 bool flag = false;
77 node *p = root, *tmp;
78 while(ch[i])
79 {
80 t = ch[i] - 31;
81 while(!p->next[t] && p != root) p = p->fail;
82 p = p->next[t];
83 if(!p) p = root;
84 tmp = p;
85 while(tmp != root && tmp->id )
86 {
87 flag = true;
88 if(!vis[tmp->id])
89 {
90 g.push_back(tmp->id);
91 vis[tmp->id]=1;
92 }
93 tmp = tmp->fail;
94 }
95 i++;
96 }
97 if(!flag) return false;
98 sort(g.begin(), g.end());
99 printf("web %d:", count);
100 for(int i = 0; i < g.size(); i++)
101 {
102 printf(" %d", g[i]);
103 }
104 printf("\n");
105 return true;
106
107 }
108
109 int main()
110 {
111 int n, total;
112 while(~scanf("%d", &n))
113 {
114 node *root = new node();
115 total = 0;
116 for(int i = 0; i < n; i++)
117 {
118 scanf("%s", ch);
119 insert(root, ch, i + 1);
120 }
121 AC(root);
122 scanf("%d", &n);
123 for(int i = 0; i < n; i++)
124 {
125 scanf("%s", ch);
126 memset(vis,0,sizeof(vis));
127 if(query(root, ch,i+1)) total++;
128 }
129 printf("total: %d\n", total);
130 }
131 return 0;
132 }

 

posted @ 2012-02-11 14:26  HUJJ  阅读(285)  评论(0编辑  收藏  举报