字典树模板
2017-08-26 19:24
375 查看
动态字典树:
//好写,速度稍慢 const int N = 100000 + 10, INF = 0x3f3f3f3f; struct trie { int val; trie *next[26]; trie() { val = 0; memset(next, 0, sizeof next); } }*root; //字典树根,记得初始化根 void trie_insert(char *s) { trie *p = root; for(int i = 0; s[i]; i++) { int j = s[i] - 'a'; if(p->next[j] == NULL) p->next[j] = new trie; p->next[j]->val++;//模板代码是求前缀为给定字符串的字符串个数 p = p->next[j]; } } int trie_query(char *s) { trie *p = root; for(int i = 0; s[i]; i++) { int j = s[i] - 'a'; if(p->next[j] == NULL) return 0; p = p->next[j]; } return p->val; } //调用此函数传入字典树根root,清空当前字典树,多实例一定要清空,单实例无所谓 void trie_del(trie *p) { for(int i = 0; i < 26; i++) if(p->next[i] != NULL) trie_del(p->next[i]); delete p; }
静态字典树:
//速度稍快,小心空间大小问题,容易RE或MLE const int N = 100000 + 10; struct node { int val; node *next[26]; }trie[N*10], *root; int tot; char s ; node* node_init() { trie[tot].val = 0; memset(trie[tot].next, 0, sizeof trie[tot].next); return trie + tot++; } void trie_init() //初始化,清空字典树,代价O(1) { tot = 0; root = node_init(); } void trie_insert(char *s) { node *p = root; for(int i = 0; s[i]; i++) { int j = s[i] - 'a'; if(p->next[j] == NULL) p->next[j] = node_init(); p->next[j]->val++;//模板代码是求前缀为给定字符串的字符串个数 p = p->next[j]; } } int trie_query(char *s) { node *p = root; for(int i = 0; s[i]; i++) { int j = s[i] - 'a'; if(p->next[j] == NULL) return 0; p = p->next[j]; } return p->val; }
相关文章推荐
- hihoCoder 1014 Trie树 字典树模板
- (模板题)poj 2418 Hardwood Species(字典树)
- HDU 4825 Xor Sum (01字典树模板题)
- 字典树模板
- trie树学习总结(字典树模板)
- 字典树模板
- 最小最大表示法,求环形字符串的最小最大字典树(模板)
- hdu 1075 What Are You Talking About 字典树模板
- 字典树模板
- Trie树 字典树 模板
- 模板 可持久化字典树
- hdu1251统计难题-字典树模板题
- Shortest Prefixes POJ - 2001 (字典树模板题~)
- trie树(字典树)模板
- 字典树(模板+总结)
- HDU 1671 Phone List 字典树模板
- hdu1247 字典树模板
- hdu1247(字典树模板)
- hdu 1251 (字典树 Trie 模板题)
- HDU1671(字典树模板题)