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

 

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

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

 

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

 

Sample Input
banana
band
bee
absolute
acm
 
ba
b
band
abc
 

 

Sample Output
2
3
1
0
 
启发博客:http://www.cnblogs.com/yym2013/p/3780621.html,以下题解摘自此博客
思路
    字典树的经典应用,给你多个单词,构建字典树,然后给你一个字符串,求以这个字符串为前缀的单词的数量。
注意
    注意如何判断空行,我用了2种方法。
    1、用strlen()计算字符串的长度,如果长度为0,说明为空行,退出输入循环。
    2、用gets()读入。读入的回车符会自动转换为NULL。所以循环读入,每次检测读入进来的字符串的第一个字符是否为NULL即可。
我用链表写了一下,因为比较好理解,但在HDU上G++内存超限,换成C++就过了

 

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cmath>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 struct trie
 8 {
 9     trie* next[26];//下一个结点
10     int num;//以当前字符串为前缀的数量
11     trie()//构造函数
12     {
13         int i;
14         for(i=0;i<26;i++)
15             next[i]=NULL;
16         num=0;
17     }
18 };
19 
20 trie root;
21 
22 void insert(char word[])
23 {
24     trie* r=&root;
25     int i;
26     for(i=0;word[i];i++)
27     {
28         if(r->next[word[i]-'a']==NULL)//这个字符没有
29             r->next[word[i]-'a']= new trie;
30         r=r->next[word[i]-'a'];
31         r->num++;
32     }
33 }
34 
35 int find(char word[])
36 {
37     trie* r=&root;
38     int i;
39     for(i=0;word[i];i++)
40     {
41         if(r->next[word[i]-'a']==NULL)
42             return 0;
43         r=r->next[word[i]-'a'];
44     }
45     return r->num;
46 }
47 
48 
49 
50 int main()
51 {
52     char word[15];
53     while(gets(word))
54     {
55         if(word[0]==NULL)
56             break;
57         insert(word);
58     }
59     while(gets(word))
60     {
61         if(word[0]==NULL)
62             break;
63         printf("%d\n",find(word));
64     }
65     return 0;
66 }