字典树
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
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
Think:
这是一道字典树的典型题目,完成建树,插入,查找的操作。开始觉得很简单,以为一会就可以写完,但是……真的是代码十分钟,bug大半天……一直是CE,总感觉很对,后来我都怀疑是编译器的问题,又找了台电脑,但还是CE……绝望啊~总之是无限心塞/^~^\
后来,终于找到了,在定义MAXM的时候,不能超过七位,不然……
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXZ 34
#define MAXM 1000000//注意不能超过七位数,否则无限CE
struct node
{
int ans;//记录到这个节点的时候,有几个单词
struct node *next[MAXZ];//树杈
};
int top;//当前所指向的字符位置
struct node Tree[MAXM];
struct node * creat()//建树
{
struct node *p = &Tree[top++];
for(int i=0;i<MAXZ;i++)
{
p->next[i] = NULL;
}
p->ans = 0;
return p;
}
struct node * Initial()//初始化
{
top = 0;
return creat();
}
void Insert(struct node * root, char *s)//插入
{
struct node *p = root;
for(int i=0;s[i];i++)
{
int t = s[i] - 'a';
if(p->next[t]==NULL)
p->next[t] = creat();
p = p->next[t];
}
p->ans++;
}
int Find(struct node * root, char *s)//返回单词的个数
{
struct node * p= root;
for(int i=0;s[i];i++)
{
int t = s[i] - 'a';
if(p->next[t]==NULL)
return 0;
p = p->next[t];
}
return p->ans;
}
int main()
{
int n, m;
char s1[121], s2[121];
while(scanf("%d %d", &n, &m)!=EOF)
{
if(n==0&&m==0)
break;
struct node * root = Initial();
while(n--)
{
scanf("%s", s1);
Insert(root, s1);
}
while(m--)
{
scanf("%s", s2);
if(Find(root, s2))
printf("Yes\n");
else
printf("No\n");
}
}
return 0;
}