hdu1521(字典树模板)

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

 

题意: 中文题诶~

 

思路: 字典树模板

 

代码1: 动态内存, 比较好理解一点, 不过速度略慢, 代码略长

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 using namespace std;
 5 
 6 const int MAXN = 26;
 7 const int MAX = 11;
 8 char str[MAX];
 9 
10 struct node{
11     int count;
12     node *next[MAXN];
13     node(){
14         count = 0;
15         for(int i = 0; i < MAXN; i++){
16             next[i] = NULL;
17         }
18     }
19 };
20 
21 void insert(node *p, char *str){
22     for(int i = 0; str[i] != '\0'; i++){
23         int cnt = str[i] - 'a';
24         if(p -> next[cnt] == NULL) p -> next[cnt] = new node();
25         p = p -> next[cnt];
26         p -> count++;
27     }
28 }
29 
30 int query(node *p, char *str){
31     for(int i = 0; str[i] != '\0'; i++){
32         int cnt = str[i] - 'a';
33         p = p -> next[cnt];
34         if(!p) return 0;
35     }
36     return p -> count;
37 }
38 
39 void Free(node *p){
40     if(!p) return;
41     for(int i = 0; i < MAXN; i++){
42         if(p -> next[i]) Free(p -> next[i]);
43     }
44     free(p);
45 }
46 
47 int main(void){
48     node *root = new node();
49     while(gets(str) && str[0] != '\0'){
50         insert(root, str);
51     }
52     while(gets(str)){
53         printf("%d\n", query(root, str));
54     }
55     Free(root);//本题为单组输入,不释放空间也没影响
56     return 0;
57 }
View Code

 

代码2: 用数组模拟, 相对代码1略微难理解一点

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 using namespace std;
 5 
 6 const int MAXN = 1e5 + 10;
 7 int trie[MAXN << 2][26], sum[MAXN << 2], num = 1;
 8 char str[11];
 9 //每个num对应一个节点,sum[i]为i出现的次数,trie[node][cnt]存储node这条链cnt节点后一个节点的位置,并标记当前节点是否存在
10 
11 void insert(void){
12     int node = 0, indx = 0;
13     while(str[indx]){
14         int cnt = str[indx++] - 'a';
15         if(!trie[node][cnt]) trie[node][cnt] = num++;
16         sum[trie[node][cnt]]++;
17         node = trie[node][cnt];
18     }
19 }
20 
21 int query(void){
22     int node = 0, indx = 0;
23     while(str[indx]){
24         int cnt = str[indx++] - 'a';
25         if(!trie[node][cnt]) return 0;
26         node = trie[node][cnt];
27     }
28     return sum[node];
29 }
30 
31 int main(void){
32     while(gets(str) && str[0] != '\0'){
33         insert();
34     }
35     while(gets(str)){
36         printf("%d\n", query());
37     }
38     return 0;
39 }
View Code

 

posted @ 2017-07-04 21:00  geloutingyu  阅读(229)  评论(0编辑  收藏  举报