HDU 1251 统计难题

统计难题

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 59770    Accepted Submission(s): 20778


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

 

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

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

 

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

 

Sample Input
banana band bee absolute acm ba b band abc
 
Sample Output
2 3 1 0
 
Trie 树入门题,注意输入即可
 1 #include <cstring>
 2 #include <iostream>
 3 #include <cstdio>
 4 
 5 using namespace std;
 6 
 7 int top, tot = 0;
 8 int t[2000020][30], cnt[2020000], endlle[2020000];
 9 char ch, las, s[20020000];
10 
11 inline bool Getstr()
12 {
13     top = 0;
14     ch = getchar();
15     if (ch == EOF) return false;
16     if (ch == '\n') return false;
17     while (ch != '\n') s[++top] = ch, ch = getchar();
18     s[++top] = '\0';
19     return true;
20 }
21 
22 inline void Insert(char *s)
23 {
24     int id, u = 0, l = strlen(s);
25     for (int i = 0; i < l; ++i)
26     {
27         ++cnt[u];
28         id = s[i] - 95;
29         if (!t[u][id]) t[u][id] = ++tot;
30         u = t[u][id];
31     }
32     endlle[u] = 1;
33 }
34 
35 inline int Find(char *s)
36 {
37     int id, u = 0, l = strlen(s);
38     for (int i = 0; i < l; ++i)
39     {
40         id = s[i] - 95;
41         if (t[u][id]) u = t[u][id];
42         else return 0;
43     }
44     return cnt[u] + endlle[u];
45 }
46 
47 int main()
48 {
49     for (;;)
50     {
51         if (!Getstr()) break;
52         Insert(s + 1);
53     }
54     for (;;)
55     {
56         if (!Getstr()) break;
57         printf("%d\n", Find(s + 1));
58     }
59     return 0;
60 }

 

posted @ 2018-12-10 07:50  Christopher_Yan  阅读(105)  评论(0编辑  收藏  举报