第十二章Trie树(字典树)解决HDU1251
2012-04-19 17:05
218 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1251
#include <iostream> using namespace std; struct TrieNode { TrieNode *children[26]; bool flag; int cnt;//前缀数目 }; void InitTrieNode(TrieNode *tn) { if(!tn) { exit(1); } for(int i=0;i<26;i++) { (tn->children)[i]=NULL; } tn->flag=false; tn->cnt=0; } //把长度为n的字符串a插入Trie树 void TrieTreeInsert(TrieNode **root,char *a,int n) { if(!(*root)) { *root=new TrieNode; InitTrieNode(*root); } TrieNode *tn=*root; for(int i=0;i<n;i++) { TrieNode *child=(tn->children)[a[i]-'a']; if(!child) { child=new TrieNode; InitTrieNode(child); (tn->children)[a[i]-'a']=child; } if(child->flag==false) { child->flag=true; child->cnt++; } else { child->cnt++; } tn=child; } } //统计以字符串b为前缀的单词数量 int Count(TrieNode *root,char *b,int n) { int cnt=0; if(root) { TrieNode *tn=root; for(int i=0;i<n;i++) { TrieNode *child=(tn->children)[b[i]-'a']; if(child) { tn=child; } else { tn=NULL; break; } } if(tn!=root && tn!=NULL) { cnt=tn->cnt; } } return cnt; } int main() { char a[10]; TrieNode *root=NULL; while(gets(a)) { int len=strlen(a); if(len==0) { break; } TrieTreeInsert(&root,a,len); } char b[10]; while(gets(b)) { int len=strlen(b); cout<<Count(root,b,len)<<endl; } return 0; }
相关文章推荐
- C++——字典树(Trie树)模板——统计难题(HDU1251)
- [复习][HDU1251]字典树(trie树)统计难题
- 字典树(Trie树)总结-hdu1251
- hdu1251 、1671、1247 字典树,,Trie树
- hdu1251-字典树
- 字典树(trie树
- 字典树(Trie树)用法及例子(一)
- B树,B+树、R树(地图)、LSM(Log-Structured Merge Tree)树、Trie树(字典树)
- 字典树(trie树)、后缀树
- Trie树解决字典中查找单词问题
- 字典树---->Trie树
- 中级篇——字典树(Trie树)
- HDU1251(静态维护字典树模板题)
- hdu1671(trie树(字典树))
- 【字典树】 hdu1251 统计难题
- HDU1251 统计难题 【trie树】
- hdu1251 字典树
- 从Trie树(字典树)谈到后缀树
- 9-11-Trie树/字典树/前缀树-查找-第9章-《数据结构》课本源码-严蔚敏吴伟民版
- Trie树 - 字典树