标签:
统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 24521 Accepted Submission(s): 10133Problem DescriptionIgnatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
Output对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Inputbananabandbeeabsoluteacmbabbandabc
Sample Output2310
AuthorIgnatius.L
坑坑:用G++在杭电oj上提交会一直内存超限~
1 #include<iostream> 2 #include<vector> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include <math.h> 7 #include<algorithm> 8 #define ll long long 9 #define eps 1e-8 10 using namespace std; 11 12 struct nodes 13 { 14 int cnt; 15 struct nodes *next[26]; 16 nodes() 17 { 18 int i; 19 cnt = 0; 20 for(i = 0; i < 26; i++) 21 next[i] = NULL; 22 } 23 } root,*temp; 24 25 void inserts(char *word) 26 { 27 nodes *cur = &root; 28 while(*word ) 29 { 30 int t = *word - ‘a‘; 31 if(cur->next[t] == NULL) 32 { 33 temp = (nodes *)malloc(sizeof(nodes)); 34 temp->cnt = 0; 35 for(int i = 0; i < 26; i++) 36 temp->next[i] = NULL; 37 cur->next[t] = temp; 38 } 39 cur = cur->next[t]; 40 cur->cnt++; 41 word++; 42 } 43 } 44 45 void searchs(char *word) 46 { 47 nodes *cur = &root; 48 int ans = 0; 49 while(*word && cur) 50 { 51 cur = cur->next[*word - ‘a‘]; 52 if(cur) 53 ans = cur->cnt; 54 else 55 { 56 ans = 0; 57 break; 58 } 59 word++; 60 } 61 printf("%d\n",ans); 62 } 63 64 int main(void) 65 { 66 char bank[22]; 67 char ss[50]; 68 69 while(gets(bank) && bank[0] ) 70 { 71 inserts(bank); 72 } 73 while(scanf("%s",ss) != -1) 74 { 75 searchs(ss); 76 } 77 return 0; 78 }
标签:
原文地址:http://www.cnblogs.com/henserlinda/p/4721169.html