HDU - 1251 统计难题

Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

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

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1
0
字典树裸题,注意没给输入大小很坑,暴力直接TLE

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 struct node{
 8     int num;
 9     node* next[26];
10     node()
11     {
12         num=0;
13         for(int i=0;i<26;i++)
14             next[i]=NULL;
15     }
16 };
17 
18 node* root=new node();
19 node* rt;
20 int id,len;
21 
22 void build(char* str)
23 {
24     rt=root;
25     len=strlen(str);
26     for(int i=0;i<len;i++)
27     {
28         id=str[i]-'a';
29         if(rt->next[id]==NULL)
30             rt->next[id]=new node();
31         rt=rt->next[id];
32         rt->num++;
33     }
34 }
35 
36 int querry(char* str)
37 {
38     rt=root;
39     len=strlen(str);
40     for(int i=0;i<len;i++)
41     {
42         id=str[i]-'a';
43         if(rt->next[id]==NULL)
44             return 0;
45         rt=rt->next[id];
46     }
47     return rt->num;
48 }
49 
50 int main()
51 {
52     char str[15];
53     while(gets(str)&&str[0])
54         build(str);
55     while(gets(str))
56     {
57         printf("%d\n",querry(str));
58     }
59     return 0;
60 }

 

posted @ 2017-08-26 08:32  西北会法语  阅读(168)  评论(0编辑  收藏  举报