字典树模板
2014-08-08 15:42
197 查看
定义一颗字典树:
定义字典树的根并初始化:
建立字典树:
查找:
struct Trie { int n; // n可以存储相关有用信息,视情况而定 Trie *next[maxn]; //maxn视字典树中有多少种元素而定 }
定义字典树的根并初始化:
Trie *root; void init() { root = (Trie *)malloc(sizeof(Trie)); root -> n = 0; for(int i = 0;i < maxn; i++) root -> next[i] = NULL; }
建立字典树:
void insert(char *word) { Trie *temp = root; for(int i = 0; i < strlen(word); i++) { int pos = word[i] - 'a'; if(temp -> next[pos] == NULL) { Trie *cur = (Trie *)malloc(sizeof(Trie)); for(int j = 0;i < maxn; i++) { cur -> next[i] = NULL; cur -> n = 0; } temp -> next[pos] = cur; } temp = temp ->next[pos]; } temp -> n = 1; // 单词结尾处标记1 }
查找:
bool search(char *word) { Trie *temp = root; for(int i = 0; i < strlen(word); i++) { temp = temp -> next[word[i] - 'a']; if(temp == NULL) return false; //没有以次为前缀的单词 if(temp -> n = 1) return true; //该单词是别的单词的前缀 } return true; //别的单词是该单词的前缀 }释放内存
void del(Trie *cur) //采用递归来释放 { for(int i = 0;i < maxn; i++) { if(cur -> next[i] != NULL) del(cur -> next[i]); } free(cur); }
相关文章推荐
- HDU 4825 Xor Sum (01字典树模板题)
- 字典树模板
- 百度之星预选赛1003字典树模板
- 字典树模板
- 【字典树模板(数组实现)】HDU 1251 统计难题
- hdu1251统计难题-字典树模板题
- Shortest Prefixes POJ - 2001 (字典树模板题~)
- 字典树模板【经测试,几个函数都好用】
- 字典树模板
- poj Shortest Prefixes 2001 (字典树模板)
- hihoCoder 1014 Trie树 字典树模板
- 字典树——字典树树模板
- 字典树--模板
- hdu1247(字典树模板)
- 字典树模板(hdu1251)
- Shortest Prefixes 字典树模板
- HDU 1251 统计难题(字典树模板题)
- ACM Trie树 字典树模板
- HDU - 1251 统计难题(字典树模板题)
- [trie]字典树模板