HDU 1251 统计难题 字典树

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

题意:

  给出你一些单词,然后在给出一些前缀,然后问你这些前缀是前面给的单词的前缀的有多少个。

 

坑爹:

  

 

 解法:

  简单字典树。

 

View Code
 1 #include<iostream>
 2 using namespace std;
 3 
 4 struct Node
 5 {
 6     int a;
 7     struct Node *son[26];
 8     int flag;
 9 };
10 struct Node *root;
11 char str[26];
12 
13 void init(struct Node **newNode)
14 {
15     *newNode = (struct Node*)malloc(sizeof(struct Node));
16     int i;
17     for(i=0; i<26; i++)
18     {
19         (*newNode)->son[i] = NULL;
20     }
21     (*newNode)->a = 1;
22     (*newNode)->flag = 0;
23 
24 }
25 
26 void insert()
27 {
28     struct Node *currNode = root;
29     int len = strlen(str);
30 
31     int i;
32     for(i=0; i<len; i++)
33     {
34         if(currNode->son[str[i]-'a'] != NULL)
35         {
36             currNode = currNode->son[str[i]-'a'];
37             currNode->a = currNode->a + 1;
38         }
39         else
40         {
41             struct Node *newNode = NULL;
42             init(&newNode);
43             currNode->son[str[i]-'a'] = newNode;
44             currNode = newNode;
45         }
46     }
47     currNode->flag++;
48 }
49 
50 int find()
51 {
52     struct Node *currNode = root;
53     int len = strlen(str);
54     if(len == 0)
55     {
56         return 0;
57     }
58     int i;
59     for(i=0; i<len; i++)
60     {
61         if(currNode->son[str[i]-'a'] != NULL)
62         {
63             currNode = currNode->son[str[i]-'a'];
64         }
65         else
66         {
67             return 0;
68         }
69     }
70     return currNode->a;
71 }
72 
73 int main()
74 {
75     init(&root);
76     while(gets(str))
77     {
78         if(strcmp(str,"") == 0)
79         {
80             break;
81         }
82         insert();
83     }
84     while(gets(str))
85     {
86         cout<<find()<<endl;
87     }
88     return 0;
89 }

 

posted @ 2012-11-03 16:50  pc....  阅读(173)  评论(0)    收藏  举报