字典树
Time Limit: 1000 ms Memory Limit: 65536 KiB
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 .
Sample Input
3 2
aab
aa
ad
ac
ad
0 0
Sample Output
No
Yes
**#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
int data;
int next[26]; //用node会爆内存
};
struct node a[1000000];
int top;
struct node*creat_kong()
{
int i;
struct node*root=&a[top++];
root->data=0;
for(i=0; i<26; i++)
{
root->next[i]=NULL;
}
return root;
}
void insert(struct node*root,char s[])
{
struct node*p=root;
int len=strlen(s);
int i,t;
for(i=0; i<len; i++)
{
t=s[i]-'a';
if(p->next[t]==NULL)
{
p->next[t]=creat_kong();
}
p=p->next[t];
}
p->data=1;
}
int find(struct node*root,char s[])
{
struct node*p=root;
int len=strlen(s);
int i,t;
for(i=0; i<len; i++)
{
t=s[i]-'a';
if(p->next[t]==NULL)
{
return 0;
}
p=p->next[t];
}
return p->data;
}
int main()
{
int n,m,i;
char s[12];
while(scanf("%d %d",&n,&m)!=EOF)
{
top=0;
struct node*root=creat_kong();
if(n==0&&m==0)
{
break;
}
for(i=0; i<n; i++)
{
scanf("%s",s);
insert(root,s);
}
while(m--)
{
scanf("%s",s);
if(find(root,s))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
}
**
**#include <stdio.h>
#include <string.h>
int top;
struct node
{
int next[26];
int flag;
} st[1001000];
int creat()
{
memset(st[top].next,-1,sizeof(st[top].next));
st[top].flag=0;
return top++;
}
void insertt(int root,char*s)
{
int len=strlen(s);
for(int i=0; i<len; i++)
{
int t=s[i]-'a';
if(st[root].next[t]==-1)
{
st[root].next[t]=creat();
}
root=st[root].next[t];
}
st[root].flag=1;
}
int cmp(char *s,int root)
{
int len=strlen(s);
for(int i=0; i<len; i++)
{
int t=s[i]-'a';
if(st[root].next[t]==-1)
{
return 0;
}
root=st[root].next[t];
}
return st[root].flag;
}
int main()
{
int n,m,root;
char s[101];
char s1[101];
while(~scanf("%d %d",&n,&m))
{
if(n==0&&m==0)
{
break;
}
top=0;
root=creat();
while(n--)
{
scanf("%s",s);
insertt(root,s);
}
while(m--)
{
scanf("%s",s1);
if(cmp(s1,root)==1)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
}
**