数据结构 字典树模板
2013-11-28 15:29
447 查看
#include "stdio.h" // 字典树模板 hdu 1251 #include "string.h" #include "stdlib.h" struct node{ struct node *next[26]; int num; }; struct node *root; void insert(char *k) { int i; struct node *a = root; while(k[0]!='\0') { if(a->next[k[0]-'a'] == NULL) { node *tt; tt = (node *)malloc(sizeof(node)); tt->num = 1; for(i=0;i<26;i++) tt->next[i] = NULL; a->next[k[0]-'a'] = tt; a = tt; //移向下一级 } else { a = a->next[k[0]-'a']; //移向下一级 a->num = a->num + 1; } k++; } } int find(char *k) { int ans; struct node *a = root; while(k[0]!='\0') { if(a->next[k[0]-'a']==NULL) return 0; else { ans = a->next[k[0]-'a']->num; a = a->next[k[0]-'a']; } k++; } return ans; } void BFS(node *k); int main() { int i; char str[15]; root = (node *)malloc(sizeof(node)); //给root指针开辟空间 for(i=0;i<26;i++) //root下的指针初始化 root->next[i] = NULL; root->num = 0; while(gets(str) && strcmp(str,"")!=0) insert(str); while(scanf("%s",str)!=-1) printf("%d\n",find(str)); BFS(root); return 0; } void BFS(node *k) //深搜去释放内存! { int i; if(k==NULL) return ; for(i=0;i<26;i++) { if(k->next[i]!=NULL) BFS(k->next[i]); } free(k); }
相关文章推荐
- hdu1247(字典树模板)
- 字典树模板
- 字典树——字典树树模板
- hdu1247 Hat’s Words(字典树:模板+枚举)
- 字典树模板(hdu1251)
- 数据结构—KMP模板
- 静态字典树和动态字典树模板
- 字典树模板
- 【模板】【字符串】Trie(前缀树、字典树)
- 2016暑期集训4——数据结构(知识点,模板,简单题题解)
- 【数据结构】树状数组模板--CODE[VS] 1080线段树练习and1081线段树练习2
- 字典树模板
- 数据结构---各种树模板
- 字典树模板。。
- ACM_字典树模板
- trie树(字典树)--模板
- (新知)数据结构--Splay--模板
- 字典树模板
- 字典树模板
- [数据结构]最小堆的类模板实现