#include<stdio.h> #include<string.h> #include<stdlib.h> #define ull unsigned long long const ull p = 1e8+7; const int mod=100003; int e,to[mod],next[mod],begin[mod]; char a[mod][12],b[mod][12]; int hashx(char *s){ int len=strlen(s); ull hs=0; for(int i=0;i<len;i++) hs=hs*p+s[i]; return hs%mod+1; } void insert(int i,char *s){ int x=hashx(s); to[++e]=i; next[e]=begin[x]; begin[x]=e; } char *find(char *s){ int x=hashx(s); for(int i=begin[x];i;i=next[i]) if(strcmp(b[to[i]],s)==0) return a[to[i]]; return NULL; } int main(){ freopen("poj2503.in","r",stdin); freopen("poj2503.out","w",stdout); char s[15],s1[15],s2[15]; int i=0; while(1){ gets(s); if(s[0] == '\0') break; ++i; sscanf(s,"%s %s", a[i], b[i]); insert(i,b[i]); } while(gets(s)!=NULL){ if(s[0]=='\0')break; char *st=find(s); if(st!=0) puts(st); else puts("eh"); } return 0; }
下面用邻接表,没有AC
#include<stdio.h> #include<string.h> #include<stdlib.h> #define ull unsigned long long const ull b = 100000007; const int mod=199999; struct node{ char word1[15],word2[15]; struct node *next; node(){ next=NULL; } }; struct node *a[300010],*p,*q; void insert(char *s1,char *s2){ int len=strlen(s1); ull t=1,hs=0; for(int i=0;i<len;i++) hs=hs*b+s1[i]; int k=hs%mod+1; p=a[k]; while(p->next!=NULL)p=p->next; q=new node; strcpy(q->word1,s1); strcpy(q->word2,s2); p->next=q; } char *find(char *s){ int len=strlen(s); ull t=1,hs=0; for(int i=0;i<len;i++) hs=hs*b+s[i]; int k=hs%mod+1; p=a[k]; if(p->next==NULL)return NULL; p=p->next; while(p!=NULL && strcmp(p->word1,s)!=0)p=p->next; if(p==NULL)return NULL; else return p->word2; } int main(){ char s[15],s1[15],s2[15]; int i,j,k,m,n; for(i=0;i<=300000;i++) a[i]=new node; while(1){ gets(s); if(s[0] == '\0') break; sscanf(s,"%s %s", s1, s2); insert(s2,s1); } while(gets(s)!=NULL){ if(s[0]=='\0')break; char *st=find(s); if(st!=0) puts(st); else puts("eh"); } return 0; }