典型的字典树 当做模板题吧!
字典树的性质:
⑴根节点不包含字符,除根节点外每一个节点都只包含一个字符。
⑵从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
⑶ 每个节点的所有子节点包含的字符都不相同。
搜索字典项目的方法为:
(1) 从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
(3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
(4) 迭代过程……
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int flag,Count;
struct node *next[26];//题中26个小写字母
};
struct node *build()//建立字典树
{
struct node *tree ;
tree = (struct node *)malloc(sizeof(struct node));
int i;
for(i=0;i<26;i++)///初始化为空
{
tree->next[i] = NULL;
}
tree->Count = 0;//查找标记为零
return tree;
};
void Insert(struct node *root,char a[])//插入
{
int i,t;
int len = strlen (a);
for(i=0;i<len;i++)
{
if(a[i]>='A'&&a[i]<='Z')//题中知道是小写字母 为了避免不知道大小写
t = a[i]-'A';
else
t = a[i]-'a';
if(root->next[t] == NULL)///一直建完树
{
root -> next[t] = build();
}
root = root->next[t];
}
root->Count = 1;
}
int Search(struct node *root,char a[])//查找
{
int i,t;
int len = strlen(a);
for(i=0;i<len;i++)
{
if(a[i]>='A'&&a[i]<='Z')
t = a[i]-'A';
else
t = a[i]-'a';
if(root->next[t] == NULL)
return 0;
root = root->next[t];
}
if(root->Count == 1)
return 1;
return 0;
}
void Delete(struct node *tree)///基本固定的清楚内存的函数
{
int i;
for(i=0;i<26;i++)
{
if(tree->next[i]!=NULL)
{
Delete(tree->next[i]);
}
}
free(tree);
}
int main()
{
char a[20014][11],b[11];
int i,n,m;
while(scanf("%d",&n),n)
{
scanf("%d",&m);
struct node *tree = build();
for(i=0;i<n;i++)
{
scanf("%s",a[i]);
}
for(i=0;i<m;i++)
{
scanf("%s",b);
Insert(tree,b);//插入
}
int sum = 0;
for(i=0;i<n;i++)
{
int A = Search(tree,a[i]);//查找
if(A == 1)
sum++;
}
printf("%d\n",n-sum);
Delete(tree);///清楚内存
}
return 0;
}
最后 , 字典树应用:
串的快速检索
给出N个单词组成的熟词表,以及一篇全用小写英文书写的文章,请你按最早出现的顺序写出所有不在熟词表中的生词。
在这道题中,我们可以用
数组枚举,用哈希,用字典树,先把熟词建一棵树,然后读入文章进行比较,这种方法效率是比较高的。
“串”排序
给定N个互不相同的仅由一个单词构成的英文名,让你将他们按
字典序从小到大输出
用字典树进行排序,采用
数组的方式创建字典树,这棵树的每个结点的所有儿子很显然地按照其字母大小排序。对这棵树进行先序遍历即
可。
最长公共前缀
对所有串建立字典树,对于两个串的最长公共前缀的长度即他们所在的结点的公共祖先个数,于是,问题就转化为当时公共祖先问题。