POJ2503字典树
此代码原始出处:http://blog.csdn.net/cnyali/article/details/47367403
#include<stdio.h> #include<string.h> #include<stdlib.h> struct node{ char word[15]; int count; struct node *next[30]; node(){ count=0; memset(next,0,sizeof(next)); } }; void insert(struct node *p,char *s1,char *s2){ int i,j,k,l=strlen(s1); struct node *q; for(i=0;i<l;i++){ k=s1[i]-'a'; if(p->next[k]==NULL){ q=new node; p->next[k]=q; } p=p->next[k]; } p->count=1; strcpy(p->word,s2); } char *find(struct node *p,char *s){ int i,j,k,l=strlen(s); for(i=0;i<l;i++){ k=s[i]-'a'; p=p->next[k]; if(p==0)return NULL; } if(p->count==1)return p->word; else return NULL; } int main(){ freopen("poj2503.in","r",stdin); freopen("poj2503.out","w",stdout); struct node *h; char s[15],s1[15],s2[15]; int i,j,k,m,n; h=new node; while(1){ gets(s); if(s[0] == '\0') break; sscanf(s,"%s %s", s1, s2); insert(h,s2,s1); } while(gets(s)!=NULL){ if(s[0]=='\0')break; char *st=find(h,s); if(st!=0) puts(st); else puts("eh"); } return 0; }