#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; }
#include<iostream> #include<cstdio> #include<cstring> using namespace std; struct node{ char word[15]; int count; node *next[30]; node(){ count=0; memset(next,0,sizeof(next)); } }; bool flag; char fy[15]; void add(node *h,char *b,char *a){ int len=strlen(b); for(int i=0;i<len;i++){ int k=b[i]-'a'; if(h->next[k]==NULL){ node *q=new node; h->next[k]=q; } h=h->next[k]; } h->count=1; strcpy(h->word,a); } void dfs(node *h,char *a){ int len=strlen(a); for(int i=0;i<len;i++){ int k=a[i]-'a'; if(h->next[k]==NULL)return; h=h->next[k]; } if(h->count==1){ flag=1;strcpy(fy,h->word); } } void out(node *h,char s){ cout<<s<<" "; for(int i=0;i<=25;i++) if(h->next[i])out(h->next[i],i+97); } int main(){ int i,j,k,m,n; char s; char a[15],b[15],c[15]; node *h=new node; while(1){ scanf("%s%c",&a,&s); if(s=='\n')break; scanf("%s",&b); add(h,b,a); } //out(h,s); flag=0; dfs(h,a); if(flag)printf("%s\n",fy); else printf("eh\n"); while(scanf("%s",&c)!=EOF){ flag=0; dfs(h,c); if(flag)printf("%s\n",fy); else printf("eh\n"); } return 0; }
POJ2503 字典树
最新推荐文章于 2021-08-07 16:18:14 发布