字符串_字典树(模板 hdu 1251)
例题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
代码:
1 #include "stdio.h" // 字典树模板题 hdu 1251 2 #include "string.h" 3 #include "stdlib.h" 4 5 struct node{ 6 int num; 7 struct node *next[26]; 8 }; 9 10 struct node *root; 11 12 void Insert(char *k) 13 { 14 int i; 15 struct node *a = root; 16 while(k[0]!='\0') 17 { 18 if(a->next[k[0]-'a'] == NULL) 19 { 20 node *tt; 21 tt = (node *)malloc(sizeof(node)); 22 tt->num = 1; 23 for(i=0;i<26;i++) tt->next[i] = NULL; 24 a->next[k[0]-'a'] = tt; 25 a = tt; //移向下一级 26 } 27 else 28 { 29 a = a->next[k[0]-'a']; //移向下一级 30 a->num = a->num + 1; 31 } 32 k++; 33 } 34 } 35 36 int Find(char *k) 37 { 38 int ans; 39 struct node *a = root; 40 while(k[0]!='\0') 41 { 42 if(a->next[k[0]-'a']==NULL) 43 return 0; 44 else 45 { 46 ans = a->next[k[0]-'a']->num; 47 a = a->next[k[0]-'a']; 48 } 49 k++; 50 } 51 return ans; 52 } 53 54 void BFS(node *k); 55 56 int main() 57 { 58 int i; 59 char str[15]; 60 root = (node *)malloc(sizeof(node)); //给root指针开辟空间 61 root->num = 0; 62 for(i=0;i<26;i++) //root下的指针初始化 63 root->next[i] = NULL; 64 while(gets(str) && strcmp(str,"")!=0) 65 Insert(str); 66 while(scanf("%s",str)!=-1) 67 printf("%d\n",Find(str)); 68 BFS(root); 69 return 0; 70 } 71 72 void BFS(node *k) //深搜去释放内存! 73 { 74 int i; 75 if(k==NULL) return ; 76 for(i=0;i<26;i++) 77 { 78 if(k->next[i]!=NULL) 79 BFS(k->next[i]); 80 } 81 free(k); 82 }