码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1251 统计难题(Tire tree)

时间:2015-08-02 23:14:27      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

                统计难题



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 Tire
 9 {
10     Tire *next[maxn];
11     int v;
12     Tire()
13     {
14         memset(next,0,sizeof(next));
15         v=0;
16     }
17 };
18 
19 Tire *root=new Tire;
20 
21 void creatTire(char *str)
22 {
23     int len=strlen(str);
24     Tire *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             Tire *q=new Tire;
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 findTire(char *str)
44 {
45     int i;
46     int len=strlen(str);
47     Tire *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         creatTire(s);
65     }
66     while(scanf("%s",s)!=EOF)
67     {
68         int ans=findTire(s);
69         printf("%d\n",ans);
70     }
71     return 0;
72 }

 

HDU 1251 统计难题(Tire tree)

标签:

原文地址:http://www.cnblogs.com/homura/p/4696909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!