字典树
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
遇到单词不认识怎么办? 查字典啊,已知字典中有n个单词,假设单词都是由小写字母组成。现有m个不认识的单词,询问这m个单词是否出现在字典中。
Input
含有多组测试用例。
第一行输入n,m (n>=0&&n<=100000&&m>=0&&m<=100000)分别是字典中存在的n个单词和要查询的m个单词.
紧跟着n行,代表字典中存在的单词。
然后m行,要查询的m个单词
n=0&&m=0 程序结束
数据保证所有的单词都是有小写字母组成,并且长度不超过10
Output
若存在则输出Yes,不存在输出No .
Example Input
3 2
aab
aa
ad
ac
ad
0 0
Example Output
No
Yes
Hint
Author
gyx
以下为accepted代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXC 26
#define MAXN 1000000
struct node
{
int cnt;
struct node *next[MAXC];
};
struct node Trie[MAXN];//字典树的静态结点数组
int top;//标记下标,记录当前在静态数组中已经用到哪里
///创建结点函数(静态),不需要手动调节
struct node * CreatTrie()
{
struct node *p = &Trie[top++];
p->cnt = 0;
for(int i = 0; i < MAXC; i++)
{
p->next[i] = NULL;
}
return p;
}
///初始化函数(静态),返回树根节点的指针
struct node * Initialize()
{
top = 0;
return CreatTrie();
}
///在字典树中插入字符串st1
void Insert(struct node *root, char *st1)
{
struct node *p = root;
for(int i = 0; st1[i] != '\0'; i++)
{
int t = st1[i] - 'a';
if(p->next[t] == NULL)
p->next[t] = CreatTrie();
p = p->next[t];
}
p->cnt++;
}
///在字典树中查找字符串st2,并返回字符串st2的数量
int Find(struct node *root, char *st2)
{
struct node *p = root;
for(int i = 0; st2[i] != '\0'; i++)
{
int t = st2[i] - 'a';
if(p->next[t] == NULL)
return 0;
p = p->next[t];
}
return p->cnt;
}
int main()
{
int n, m;
char st1[14], st2[14];
while(scanf("%d %d", &n, &m) != EOF)
{
struct node *root = Initialize();//初始化
while(n--)
{
scanf("%s", st1);
Insert(root, st1);//插入
}
while(m--)
{
scanf("%s", st2);
if(Find(root, st2))//查询
printf("Yes\n");
else
printf("No\n");
}
}
return 0;
}
/***************************************************
User name: jk160630
Result: Accepted
Take time: 164ms
Take Memory: 1568KB
Submit time: 2017-02-10 17:40:13
****************************************************/
本文介绍了一种利用字典树进行高效单词查询的方法。通过构建字典树,可以快速判断给定单词是否存在于字典中。文章提供了一个C语言实现的例子,包括字典树的创建、插入和查找操作。
9万+

被折叠的 条评论
为什么被折叠?



