HDU 1251 统计难题(Trie tree)

                统计难题



Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 

 

Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.
 

 

Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 

 

Sample Input
banana
band
bee
absolute
acm
 
ba
b
band
abc
 

 

Sample Output
2
3
1
0
 
 1 #include<cstdio>
 2 #include<malloc.h>
 3 #include<cstring>
 4 using namespace std;
 5 
 6 const int maxn=26;
 7 
 8 struct Trie
 9 {
10     Trie *next[maxn];
11     int v;
12     Trie()
13     {
14         memset(next,0,sizeof(next));
15         v=0;
16     }
17 };
18 
19 Trie *root=new Trie;
20 
21 void creatTrie(char *str)
22 {
23     int len=strlen(str);
24     Trie *p=root;
25     for(int i=0;i<len;i++)
26     {
27         int id=str[i]-'a';
28         if(p->next[id]==NULL)
29         {
30             Trie *q=new Trie;
31             q->v=1;
32             p->next[id]=q;
33             p=p->next[id];
34         }
35         else
36         {
37             p->next[id]->v++;
38             p=p->next[id];
39         }
40     }
41 }
42 
43 int findTrie(char *str)
44 {
45     int i;
46     int len=strlen(str);
47     Trie *p=root;
48     for(i=0;i<len;i++)
49     {
50         int id=str[i]-'a';
51         if(p->next[id]==NULL)
52             return 0;
53         p=p->next[id];
54     }
55     return p->v;
56 }
57 
58 int main()
59 {
60     //freopen("in.txt","r",stdin);
61     char s[11];
62     while(gets(s)&&s[0]!='\0')
63     {
64         creatTrie(s);
65     }
66     while(scanf("%s",s)!=EOF)
67     {
68         int ans=findTrie(s);
69         printf("%d\n",ans);
70     }
71     return 0;
72 }

 

 

posted on 2015-08-02 22:23    阅读(142)  评论(0)    收藏  举报

导航