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

HDU 1251 统计难题

时间:2014-08-30 16:20:09      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   java   ar   for   

统计难题

Time Limit: 2000ms
Memory Limit: 65535KB
This problem will be judged on HDU. Original ID: 1251
64-bit integer IO format: %I64d      Java class name: Main
 
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 

Input

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

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

Output

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

Sample Input

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1
0

解题:trie

bubuko.com,布布扣
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <climits>
 7 #include <vector>
 8 #include <queue>
 9 #include <cstdlib>
10 #include <string>
11 #include <set>
12 #include <stack>
13 #define LL long long
14 #define pii pair<int,int>
15 #define INF 0x3f3f3f3f
16 using namespace std;
17 struct trie{
18     int wd[27],cnt;
19     trie(){
20         memset(wd,-1,sizeof(wd));
21         cnt = 0;
22     }
23 };
24 trie dic[500000];
25 int tot = 1;
26 void insertWd(int root,char *s){
27     for(int i = 0; s[i]; i++){
28         if(dic[root].wd[s[i]-a] == -1){
29             dic[root].wd[s[i]-a] = tot++;
30         }
31         root = dic[root].wd[s[i]-a];
32         dic[root].cnt++;
33     }
34 }
35 int query(int root,char *s){
36     for(int i = 0; s[i]; i++){
37         if(dic[root].wd[s[i]-a] == -1) return 0;
38         root = dic[root].wd[s[i]-a];
39     }
40     return dic[root].cnt;
41 }
42 char str[20000];
43 int main() {
44     int root = 0;
45     while(gets(str) && str[0]) insertWd(root,str);
46     while(gets(str) && str[0]) printf("%d\n",query(root,str));
47     return 0;
48 }
View Code

 

HDU 1251 统计难题

标签:style   blog   http   color   os   io   java   ar   for   

原文地址:http://www.cnblogs.com/crackpotisback/p/3946469.html

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