找前缀个数。主要是理解trie树的含义吧,统计一个节点出现的次数就可以了。
1 #include<stdio.h> 2 #include<malloc.h> 3 #include<string.h> 4 #define MAXNUM 26 5 typedef struct tnode 6 { 7 int mark,count; 8 tnode *next[MAXNUM]; 9 10 }tnode; 11 tnode *root; 12 void init() 13 { 14 int i; 15 root=(tnode*)malloc(sizeof(tnode)); 16 for(i=0;i<MAXNUM;i++) 17 root->next[i]=NULL; 18 root->mark=0; 19 20 } 21 void insert(char *str) 22 { 23 tnode *r=root,*child; 24 int i,flag=0; 25 while(*str!='\0') 26 { 27 if(r->next[*str-'a']==NULL) 28 { flag=1; 29 child=(tnode*)malloc(sizeof(tnode)); 30 for(i=0;i<MAXNUM;i++) 31 child->next[i]=NULL; 32 child->mark=0; 33 child->count=0; 34 r->next[*str-'a']=child; 35 36 37 } 38 r->next[*str-'a']->count++; 39 r=r->next[*str-'a']; 40 str++; 41 42 } 43 44 r->mark=1; 45 46 } 47 void del(tnode *r) 48 { 49 for(int i=0;i<MAXNUM;i++) 50 { 51 if(r->next[i]!=NULL) 52 del(r->next[i]); 53 } 54 free(r); 55 } 56 int search(char *str) 57 { 58 tnode *r=root; 59 int i,len; 60 len=strlen(str); 61 i=0; 62 while(r->next[*str-'a']!=NULL) 63 { 64 if(i==len-1) return r->next[*str-'a']->count; 65 r=r->next[*str-'a']; 66 str++; 67 i++; 68 69 } 70 return 0; 71 } 72 73 int main() 74 { 75 char str[15]; 76 int count; 77 gets(str); 78 init(); 79 while(strcmp(str,"")!=0) 80 { 81 insert(str); 82 gets(str); 83 } 84 while(scanf("%s",str)!=EOF) 85 { 86 count=search(str); 87 printf("%d\n",count); 88 89 } 90 91 92 93 94 95 return 0; 96 }