题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
题解:字典树模版题,
Trie树|字典树的简介及实现(转)
Trie,又称字典树、单词查找树,是一种树形结构,用于保存大量的字符串。它的优点是:利用字符串的公共前缀来节约存储空间。相对来说,Trie树是一种比较简单的数据结构.理解起来比较简单,正所谓简单的东西也得付出代价.故Trie树也有它的缺点,Trie树的内存消耗非常大.当然,或许用左儿子右兄弟的方法建树的话,可能会好点.
其基本性质可以归纳为:
1. 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
2. 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
3. 每个节点的所有子节点包含的字符都不相同。
其基本操作有:查找 插入和删除,当然删除操作比较少见.我在这里只是实现了对整个树的删除操作,至于单个word的删除操作也很简单.
搜索字典项目的方法为:
(1) 从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
(3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
(4) 迭代过程……
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
其他操作类似处理.
其他操作类似处理.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
struct node *child[26];//存储下一个字符
int cnt;//当前单词出现的次数
}node,*Trie;
Trie root;//字典树的根节点
void insert(char *str)
{
int i,j,index,len;
Trie current,newnode;
len=strlen(str);
if(len==0)
return;//单词长度为0
current=root;//当前节点为根节点
for(i=0;i<len;++i)
{
index=str[i]-'a';
if(current->child[index]!=NULL)//字典树存在该字符
{
current=current->child[index];
(current->cnt)++;//当前单词出现+1
}
else
{
newnode=(struct node *)malloc(sizeof(struct node));//新增一节点
for(j=0;j<26;++j)
newnode->child[j]=NULL;
newnode->cnt=0;
current->child[index]=newnode;
current=newnode;//修改当前节点
current->cnt=1;//此单词出现一次
}
}
}
int query(char *str)
{
int i,index,len;
Trie current;
len=strlen(str);
if(len==0)
return 0;
current=root;//从根节点开始查找
for(i=0;i<len;++i)
{
index=str[i]-'a';
if(current->child[index]!=NULL)
current=current->child[index];
else
return 0;//字典树不存在此单词
}
return current->cnt;//返回单词出现次数
}
void Del(Trie root)//释放内存
{
int i;
if(root==NULL)
return;
for(i=0;i<26;++i)
{
if(root->child[i]!=NULL)
Del(root->child[i]);
}
free(root);
root=NULL;
}
int main()
{
int i;
char str[12];
root=(struct node *)malloc(sizeof(struct node));
for(i=0;i<26;++i)
root->child[i]=NULL;
root->cnt=0;
while(gets(str))
{
if(strcmp(str,"")==0)
break;
insert(str);
}
while(scanf("%s",str)!=EOF)
printf("%d\n",query(str));
Del(root);
return 0;
}
#include <stdio.h>
#include <string.h>
#define MAXN 500005
int tot;
typedef struct trie
{
int cnt;//当前单词出现的次数
struct trie *child[26];
}trie;
struct trie Trie[MAXN];
struct trie *root;
trie *newtrie()
{//静态分配空间
int i;
trie *ptr;
ptr=&Trie[tot++];
ptr->cnt=1;
for(i=0;i<26;++i)
ptr->child[i]=NULL;
return ptr;
}
void insert(char *str)
{
int i,len,index;
trie *ptr=root;
len=strlen(str);
if(len==0)
return;
for(i=0;i<len;++i)
{
index=str[i]-'a';
if(ptr->child[index]!=NULL)
(ptr->child[index]->cnt)++;
else
ptr->child[index]=newtrie();//新增一节点
ptr=ptr->child[index];//更新节点
}
}
int query(char *str)
{
int i,len,index;
trie *ptr=root;
len=strlen(str);
if(len==0)
return 0;
for(i=0;i<len;++i)
{
index=str[i]-'a';
if(ptr->child[index]!=NULL)
ptr=ptr->child[index];
else
return 0;//字典树不存在此单词
}
return ptr->cnt;//返回此单词出现的次数
}
int main()
{
char str[12];
tot=0;
root=newtrie();
while(gets(str))
{
if(strcmp(str,"")==0)
break;
insert(str);
}
while(scanf("%s",str)!=EOF)
printf("%d\n",query(str));
return 0;
}