您的位置:首页 > 其它

POJ2503 - Babelfish - 字典树

2014-08-03 16:06 423 查看
#include<stdio.h>
#include<string.h>
struct tree
{
int count;
tree *next[30];
char c[20];
tree()
{
count=0;
for(int i=0;i<26;i++)
{
next[i]=NULL;
}
}
}*root;
void build(char *ch,char *word)
{
tree *item=root;
for(int i=0;word[i]!=NULL;i++)
{
int j=word[i]-'a';
if(item->next[j]==NULL)
{
item->next[j]=new tree;
}
item=item->next[j];
}
item->count=1;
strcpy(item->c,ch);
}
void find(char *word)
{
tree *item=root;
for(int i=0;word[i]!=NULL;i++)
{
int j=word[i]-'a';
if(item->next[j]==NULL)
{
puts("eh");
return ;
}
item=item->next[j];
}
if(item->count==1)
{
printf("%s\n",item->c);
return ;
}
else
{
puts("eh");
return ;
}
}
int main()
{
root=new tree;
char word[30];
char ch[20];
int i;
while(1)
{
gets(word);
if(strlen(word)==0)
{
break;
}
for(i=0;word[i]!=' ';i++)
{
ch[i]=word[i];
}
ch[i]=NULL;
int t=i;
for(i=0;word[t+i];i++)
{
word[i]=word[i+t+1];
}
word[i]=NULL;
build(ch,word);
}
while(gets(word)!=NULL)
{
find(word);
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: