Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 22730 | Accepted: 9756 |
Description
Input
Output
Sample Input
dog ogday cat atcay pig igpay froot ootfray loops oopslay atcay ittenkay oopslay
Sample Output
cat eh loops
题目大意: 一本方言字典,字典中可查到每个方言中单词对应的英文。 输入 英文单词,方言单词, 以一个空行表示字典输入结束。。。然后输入想要查找的方言单词,如果字典中有这个单词,输出英文单词。没有就输出eh。
思路:这道题一开始很容易想到hash,但hash 我现在还不太会。所以用了二分。hash的代码写了再贴。下面是二分查找的代码和思路。 这题学了 sscanf。 同时这道题 还有一个收获就是学会调用c语言库函数 bsearch。两段代码,一段没调用bsearch。一段是调用了bsearch的。关于qsort和 bsearch的细节博客中转载了两篇文章。 很有收获。
//Memory: 2516 KB Time: 360 MS //Language: C++ Result: Accepted #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct w { char eng[12],dia[12]; }WORD; WORD word[100100]; int cmp(const void *a,const void *b) //qsort 的比较函数。 { return strcmp( (*(WORD *)a).dia, (*(WORD *) b).dia); } int main() { //freopen("1.txt","r",stdin); int i,len; char temp[25]; for(i=0;;i++) { gets(temp); if(temp[0]=='\0') break; sscanf(temp,"%s%s",word[i].eng,word[i].dia); //刚做此题 输入有点问题 但看了sscanf就很容易 } len=i; qsort(word,len,sizeof(word[0]),cmp); //排序 char goal[12]; while(scanf("%s",goal)!=EOF) { int min=0,max=len,mid,ok=0; while(min<=max) //二分查找。 { mid=(min+max)/2; if(strcmp(word[mid].dia,goal)==0) { printf("%s\n",word[mid].eng) ; ok=1; break; } else if(strcmp(word[mid].dia,goal)>0) max=mid-1; else min=mid+1; } if(!ok) printf("eh\n"); } return 0; }
// 学到了 bsearch 函数的调用 #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct w { char eng[12],dia[12]; }WORD; WORD word[100100]; int qcmp(const void *a,const void *b) { return strcmp( (*(WORD *)a).dia, (*(WORD *) b).dia); } int bcmp(const void *c,const void *d) //bsearch 的比较函数 { return strcmp((char *)c,(* (WORD *)d).dia ); } int main() { //freopen("1.txt","r",stdin); int i,len; char temp[25]; for(i=0;;i++) { gets(temp); if(temp[0]=='\0') break; sscanf(temp,"%s%s",word[i].eng,word[i].dia); } len=i; qsort(word,len,sizeof(word[0]),qcmp); char goal[12]; while(scanf("%s",goal)!=EOF) { WORD *p=(WORD *) bsearch(goal,word,len,sizeof(word[0]),bcmp); //直接调用 if(!p) printf("eh\n"); else printf("%s\n",p->eng); } return 0; }