首次认识到Trie树的强大之处!简单易懂,只要对建立一般的树的方法有所了解就OK了。Trie树,又称单词查找树键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。

它有3个基本特性:

  1)根节点不包含字符,除根节点外每一个节点都只包含一个字符。

  2)从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。

  3)每个节点的所有子节点包含的字符都不相同。

http://poj.org/problem?id=2001

1 #include<iostream>
2  using namespace std;
3  const int chars = 26;
4  struct Trinode{
5 int num;
6 Trinode *next[chars];
7 Trinode(){
8 num = 0;
9 memset(next,0,sizeof(next));
10 }
11 };
12
13 Trinode *root = new Trinode;
14
15  void insert(char* str){
16 int i = 0;
17 Trinode *temp = root;
18 while(str[i]){//字符串遇到'/0'退出循环
19   int nextPos = str[i]-'a';
20 if(temp->next[nextPos]==0)
21 temp->next[nextPos] = new Trinode;
22
23 temp = temp->next[nextPos];
24 temp->num++;
25 i++;
26 }
27 }
28
29  void search(char *str){
30 int i = 0;
31 Trinode*temp = root;
32 while(str[i]){
33 int nextPos = str[i]-'a';
34 if(temp->num==1)
35 return;
36 cout<<str[i];
37 temp = temp->next[nextPos];
38 i++;
39 }
40 }
41  int main(){
42 char str[1001][22];
43 int count = 0;
44 while(scanf("%s",str[count])!=EOF){
45 insert(str[count]);
46 count++;
47 }
48 for(int i=0;i<count;i++){
49 cout<<str[i]<<" ";
50 search(str[i]);
51 cout<<endl;
52 }
53 return 0;
54 }

附上一份儿完整的字典树模板:

 http://www.cnblogs.com/guzhoudiaoke/archive/2011/09/08/2171262.html

posted on 2011-05-17 07:37  geeker  阅读(791)  评论(0编辑  收藏  举报