统计难题
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 131070/65535K (Java/Other)
Total Submission(s) : 17 Accepted Submission(s) : 12
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串. 注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1 0
Author
Ignatius.L
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 typedef struct Trie 5 { 6 struct Trie*Node[26]; 7 int num; 8 }Trie_Node; 9 Trie_Node*Head; 10 11 Trie_Node* New_Node() 12 { 13 Trie_Node*H; 14 int i; 15 H=(Trie_Node*)malloc(sizeof(Trie_Node)); 16 for(i=0;i<=25;i++) 17 H->Node[i]=NULL; 18 H->num=0; 19 return H; 20 } 21 22 void Insert_Trie(char STR[]) 23 { 24 Trie_Node *t; 25 Trie_Node *h=Head; 26 int i,Len=strlen(STR),SIGN; 27 for(i=0;i<Len;i++) 28 { 29 SIGN=STR[i]-'a'; 30 if(h->Node[SIGN]==NULL) 31 { 32 t=New_Node(); 33 h->Node[SIGN]=t; 34 } 35 h=h->Node[SIGN]; 36 h->num++; 37 } 38 } 39 40 int Find_Trie(char STR[]) 41 { 42 Trie_Node *h=Head; 43 int i,Len=strlen(STR),SUM,SIGN; 44 for(i=0;i<Len;i++) 45 { 46 SIGN=STR[i]-'a'; 47 if(h->Node[SIGN]==NULL) 48 { 49 SUM=0; 50 return SUM; 51 } 52 else 53 { 54 h=h->Node[SIGN]; 55 SUM=h->num; 56 } 57 58 } 59 return SUM; 60 } 61 62 int main() 63 { 64 int SUM=0; 65 char STR[20]; 66 Head=New_Node(); 67 while(gets(STR),strlen(STR)!=0) 68 Insert_Trie(STR); 69 while(gets(STR)) 70 { 71 SUM=Find_Trie(STR); 72 printf("%d\n",SUM); 73 } 74 return 0; 75 }