又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来节约存储空间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。
字典树与字典很相似,当你要查一个单词是不是在字典树中,首先看单词的第一个字母是不是在字典的第一层,如果不在,说明字典树里没有该单词,如果在就在该字母的孩子节点里找是不是有单词的第二个字母,没有说明没有该单词,有的话用同样的方法继续查找.字典树不仅可以用来储存字母,也可以储存数字等其它数据。
Trie的数据结构定义:next是表示每层有多少种类的数,如果只是小写字母,则26即可,若改为大小写字母,则是52,若再加上数字,则是62了,这里根据题意来确定。
v可以表示一个字典树到此有多少相同前缀的数目,这里根据需要应当学会自由变化。
Trie的查找(最主要的操作):
(1) 每次从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索; (3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
(4) 迭代过程……
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
这里给出生成字典树和查找的模版:
生成字典树:
接下来是查找的过程了:
题目分析+解答报告:
HDOJ 1251 统计难题:
http://www.wutianqi.com/?p=1364
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct dictree
{
struct dictree *child[26];
int n;
};
struct dictree *root;
void Insert(char *source) //插入
{
int len,i,j;
struct dictree *current,*newnode;
len=strlen(source);
if(len==0)
return;
current=root;
for(i=0;i<len;i++)
{
if(current->child[source[i]-'a']!=0)
{
current=current->child[source[i]-'a'];
current->n=current->n+1;
}
else
{
newnode=(struct dictree *)malloc(sizeof(struct dictree));
for(j=0;j<26;j++)
newnode->child[j]=0;
current->child[source[i]-'a']=newnode;
current=newnode;
current->n=1;
}
}
}
int find(char *source)
{
int i,len;
struct dictree *current;
len=strlen(source);
if(len==0) return 0;
current=root;
for(i=0;i<len;i++)
{
if(current->child[source[i]-'a']!=0)
current=current->child[source[i]-'a'];
else return 0;
}
return current->n;
}
int main()
{
freopen("in.txt","r",stdin);
char temp[11];
int i;
root=(struct dictree *)malloc(sizeof(struct dictree));
for(i=0;i<26;i++)
root->child[i]=0;
root->n=2;
while(gets(temp),strcmp(temp,"")!=0)
Insert(temp);
while(scanf("%s",temp)!=EOF)
{
i=find(temp);
printf("%d\n",i);
}
return 0;
}