字典树模板
2017-07-31 15:28
330 查看
字典树
又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
//字典树模板 #include <stdio.h> #include <iostream> #include <stdlib.h> #define MAX 26 using namespace std; typedef struct TrieNode { bool isStr; //标记该节点处是否构成单词 struct TrieNode *next[MAX]; //儿子分支 }Trie; //建树 void insert(Trie *root, const char *s) { if(root==NULL || *s=='\0') return; Trie *p = root; p->isStr = false; while(*s!='\0') { if(p->next[*s-'a']==NULL) //不在树中 { Trie *temp = (Trie *)malloc(sizeof(Trie)); temp->isStr = false; for(int i=0; i<MAX; i++) temp->next[i] = NULL; p->next[*s - 'a'] = temp; p = temp; } else { p = p->next[*s - 'a']; } s++; } p->isStr = true; //最末尾标记为有这个单词 } //查询 bool reach(Trie *root, char *s) { Trie *q = root; while(q!=NULL && *s!='\0') { q = q->next[*s-'a']; s++; } if(q!=NULL && q->isStr) return true; return false; } //释放空间 void del(Trie *root) { if(root!=NULL) { for(int i=0; i<MAX; i++) { if(root->next[i]!=NULL) del(root->next[i]); } free(root); } } int main() { int n; Trie *t = (Trie *)malloc(sizeof(Trie)); for(int i=0; i<MAX; i++) t->next[i] = NULL; scanf("%d", &n); //建立字典树 for(int i=0; i<n; i++) { char s[105]; scanf("%s", s); insert(t, s); } int m; scanf("%d", &m); //m次查找 while(m--) { char s[105]; scanf("%s", s); if(reach(t, s)) printf("%s 存在\n", s); else printf("%s 不存在\n", s); } del(t); //释放空间 return 0; }
相关文章推荐
- Hdu 1671 -Phone List (字典树模板)
- 字典树模板
- 字符串_字典树(模板 hdu 1251)
- 字典树模板
- C#字典树(字母树)的模板
- 字典树模板
- POJ1251 难题统计 字典树模板
- ACM_字典树模板
- hdu1671Phone List(字典树模板)
- Codeforces Round #367 (Div. 2) [D] Vasiliy's Multiset(01字典树模板)
- 字典树模板及讲解 http://www.cnblogs.com/tanky_woo/archive/2010/09/24/1833717.html
- 静态字典树和动态字典树模板
- 字典树模板
- poj Shortest Prefixes 2001 (字典树模板)
- 一些字典树模板
- 字典树模板
- 字典树模板
- 字典树模板 hdu1251统计难题
- 字典树模板
- 字典树模板