统计难题(字典树模板)

个人心得:先来了解下字典树的概念吧。

Trie树,即字典树,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。

Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。

它有3个基本性质:

1,根节点不包含字符,除根节点外每一个节点都只包含一个字符。

2,从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。

3,每个节点的所有子节点包含的字符都不相同

用自己的理解是就是根据前缀建立字典树,如果输入的字符串存在相同前缀那么此时这个数节点sum加一,否则建立新的子树,查找的时候

直接找到底的节点,输出节点数据就好了。

题目:

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

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

注意:本题只有一组测试数据,处理到文件结束. 
Output对于每个提问,给出以该字符串为前缀的单词的数量. 
Sample Input

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1
0
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<iomanip>
 6 #include<algorithm>
 7 using namespace std;
 8 #define inf 1<<29
 9 #define nu 4000005
10 #define maxnum 200005
11 #define num 26
12 int n;
13 typedef struct T
14 {
15     int sum;
16     struct T *next[num];
17 }TireLode,*Tire;
18 
19 TireLode tire;
20 void createTire(char *str)
21 {
22     int len=strlen(str);
23     Tire p=&tire,q;
24     for(int i=0;i<len;i++){
25         int place=str[i]-'a';
26         if(p->next[place]==NULL){
27             q=(Tire)malloc(sizeof(TireLode));
28             q->sum=1;
29             for(int j=0;j<num;j++)
30                 q->next[j]=NULL;
31                 p->next[place]=q;
32                 p=q;
33     }
34     else
35     {
36         p->next[place]->sum++;
37         p=p->next[place];
38     }
39     }
40 }
41 int FindTire(char *str)
42 {
43     int len=strlen(str);
44     Tire p=&tire;
45     for(int i=0;i<len;i++)
46     {
47         int place=str[i]-'a';
48         p=p->next[place];
49         if(p==NULL)
50              return 0;
51     }
52     return p->sum;
53 }
54 int main()
55 {
56      char str[15];
57     int i;
58     for(i=0;i<num;i++)
59          tire.next[i]=NULL;
60     while(gets(str)&&str[0]!='')
61         createTire(str);
62         while(scanf("%s",str)!=EOF)
63         {
64             printf("%d
",FindTire(str));
65         }
66     return 0;
67 }


原文地址:https://www.cnblogs.com/blvt/p/7922295.html