HDOJ1251 HDOJ1671 字典树

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

 

代码
1 #include <iostream>
2 #include <cstring>
3  using namespace std;
4
5  struct Node
6 {
7 int count;
8 Node *child[26];
9 Node() : count(0)
10 {
11 for(int i = 0; i < 26; i++)
12 child[i] = NULL;
13 }
14 }*root;
15
16  void insert(char *s)
17 {
18 Node *r = root;
19 for (int i = 0; s[i] != '\0'; i++)
20 {
21 if (r->child[s[i] - 'a'] == NULL)
22 r->child[s[i] - 'a'] = new Node();
23 r = r->child[s[i] - 'a'];
24 r->count++;
25 }
26 }
27
28  int search(char *s)
29 {
30 Node *r = root;
31 for (int i = 0; s[i] != '\0'; i++)
32 {
33 if (r->child[s[i] - 'a'] == NULL) return 0;
34 r = r->child[s[i] - 'a'];
35 }
36 return r->count;
37 }
38
39  int main()
40 {
41 char str[15];
42 root = new Node();
43 while (gets(str) && strcmp(str, "")) insert(str);
44 while (gets(str)) printf("%d\n", search(str));
45 }

 

需要判断结束标记的字典树,比上面那个稍微麻烦一点,加一个结尾标记就可以了。

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

 

代码
1 #include <iostream>
2  using namespace std;
3
4  int loc;
5  char str[11];
6  struct Node
7 {
8 bool end;
9 Node* next[10];
10
11 void init()
12 {
13 end = false;
14 for (int i = 0; i < 10; i++)
15 next[i] = NULL;
16 }
17 } node[1000000];
18
19  bool push(char* str)
20 {
21 Node* p = &node[0];
22 for (int i = 0; str[i]; i++)
23 {
24 int k = str[i] - '0';
25 if (p->next[k] == NULL)
26 {
27 p->next[k] = &node[++loc];
28 p = p->next[k];
29 p->init();
30 }
31 else
32 {
33 p = p->next[k];
34 if (!str[i+1]) return false;
35 if (p->end == 1) return false;
36 }
37 if (!str[i+1]) p->end = true;
38 }
39 return true;
40 }
41
42  int main()
43 {
44 int t, n;
45 for (cin >> t; t--;)
46 {
47 loc = 0;
48 bool flag = true;
49 node[0].init();
50 for (cin >> n; n--;)
51 {
52 cin >> str;
53 if (flag) flag = push(str);
54 }
55 puts(flag ? "YES" : "NO");
56 }
57 }

 

 

posted @ 2010-03-21 22:46  笨熊蜗居地  阅读(276)  评论(0编辑  收藏  举报