hdu 1251 统计难题 (字典树)

统计难题
Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 56842    Accepted Submission(s): 19892

Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
 
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
 
Sample Output
2
3
1
0

 

C/C++:

 1 #include <map>
 2 #include <queue>
 3 #include <cmath>
 4 #include <vector>
 5 #include <string>
 6 #include <cstdio>
 7 #include <cstring>
 8 #include <climits>
 9 #include <iostream>
10 #include <algorithm>
11 #define INF 0x3f3f3f3f
12 using namespace std;
13 const int my_max = 1e6 + 10;
14 
15 struct node
16 {
17     int id, cnt, next[26];
18 }my_node[my_max];
19 int flag = 0;
20 
21 void my_init(int x)
22 {
23     for (int i = 0; i < 26; ++ i)
24         my_node[x].next[i] = -1;
25 }
26 
27 void my_insert(char *s, int len, int x)
28 {
29     int now = 0;
30     for (int i = 0; i < len; ++ i)
31     {
32         if (my_node[now].next[s[i] - 'a'] == -1)
33         {
34             my_node[now].next[s[i] - 'a'] = ++ flag;
35             my_init(flag);
36             now = flag;
37         }
38         else now = my_node[now].next[s[i] - 'a'];
39         if (my_node[now].id != x) my_node[now].cnt ++;
40         my_node[now].id = x;
41     }
42 }
43 
44 int my_find(char *s, int len)
45 {
46     int now = 0;
47     for (int i = 0; i < len; ++ i)
48     {
49         if (my_node[now].next[s[i] - 'a'] == -1) return 0;
50         now = my_node[now].next[s[i] - 'a'];
51     }
52     return my_node[now].cnt;
53 }
54 
55 int main()
56 {
57     char s[15];
58     my_init(0);
59     int n = 1;
60     while (gets(s), s[0] != '\0')
61         my_insert(s, strlen(s), n ++);
62     while (~scanf("%s", s))
63         printf("%d\n", my_find(s, strlen(s)));
64     return 0;
65 }

 

posted @ 2018-08-22 08:29  GetcharZp  阅读(120)  评论(0编辑  收藏  举报