HDU-1251 统计难题

统计难题

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


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

注意:本题只有一组测试数据,处理到文件结束.
 
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 
 
Sample Input
banana
band
bee
absolute
acm
 
 
ba
b
band
abc
 
 
Sample Output
2
3
1
0

典型的字典树模板题,但是oj判定很迷,交G++会爆内存,要交c++才可以。

记得改头文件。

AC代码:

 1 //#include<bits/stdc++.h>
 2 #include<iostream>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 struct node{
 8     int count;
 9     node*next[26];
10     node(){
11         count=0;
12         for(int i=0;i<26;i++){
13             next[i]=NULL;
14         } 
15     }
16 };
17 
18 node* root=new node();
19 node* rt;
20 
21 int cnt,len;
22 
23 void insert(char str[30]){
24     rt=root;
25     len=strlen(str);
26     for(int i=0;i<len;i++){
27         cnt=str[i]-'a';
28         if(rt->next[cnt]==NULL)
29         rt->next[cnt]=new node();
30         rt=rt->next[cnt];
31         rt->count++;
32     }
33 }
34 
35 int search(char str[30]){
36     rt=root;
37     len=strlen(str);
38     for(int i=0;i<len;i++){
39         cnt=str[i]-'a';
40         if(rt->next[cnt]==NULL){
41             return 0;
42         }
43         rt=rt->next[cnt];
44     }
45     return rt->count;
46 }
47 
48 int main(){
49     char str[30];
50     while(gets(str)&&str[0]){
51         insert(str);
52     }
53     while(gets(str)){
54         cout<<search(str)<<endl;
55     }
56     return 0;
57 } 
原文地址:https://www.cnblogs.com/Kiven5197/p/6561417.html