POJ2503 - Babelfish - 字典树

来源:互联网 发布:大芒果数据库 编辑:程序博客网 时间:2024/06/13 04:00
#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);}}


                                             
0 0
原创粉丝点击