题目大意:给你一本字典,左边是英文,右边是火星文(这是我这么说的。。),然后输入火星文,是否能找到相应的翻译,有则输出翻译,无则输出eh。
题目链接:http://poj.org/problem?id=2503
方法:数组排序及二分查找
思路:其实这道题我也是了解了bsearch函数与qsort函数后做的,一开始还真没想出来,如果有不懂这两个函数的,可以看我上一篇介绍再看这道题,会更方便理解,过程大致就是先存入字典,我定义了一个结构体,这样将英文和火星文联系在一起,防止后面排序的时候又要在替换英文的位置,比较麻烦,直接排序结构体就行,这样写比较函数时可以通过比较结构体中的火星文来排,这样结构体中的英文也随之移动,比较方便。输入就是要遇到一行空格字典结束,然后在进行输入火星文判断是否有翻译,这可以用bsearch来寻找是否结构体数组有相同的火星文,从而实现算法。
算法实现:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct dic//定义结构体,使翻译与原语联系在一起。
{
char eng[11];//翻译。
char fn[11];//原语。
};
struct dic a[1000001];
int fcmp(const void * a,const void *b)// 定义qsort比较函数
{
return strcmp(((dic*)a)->fn, ((dic*)b)->fn);
}
int cmp(const void* a, const void* b)// 定义bsearch比较函数
{
return strcmp((char*)a, ((dic*)b)->fn);
}
int main()
{
int i,j,k,sum,sign,len;
char str[30];
struct dic *p;
sum=0;
sign=0;
while(gets(str))
{
len=strlen(str);
if(len==0)//读取的为空行则字典输入完毕。
break;
else//否则分段存储翻译与原语。
{
for(i=0;i<len;i++)
{
if(str[i]==' ')
break;
a[sum].eng[i]=str[i];
}
a[sum].eng[i]='\0';//记的字符串最后一位为'\0'。
for(j=i+1,k=0;j<len;j++,k++)
a[sum].fn[k]=str[j];
a[sum].fn[k]='\0';
sum++;
}
}
qsort(a,sum,sizeof(dic),fcmp);//将数组升序排列。
while(gets(str))
{
p=(dic*)bsearch(str,a,sum,sizeof(dic),cmp);//进行二分查找,返回结构体类型指针。
if(p)
puts(p->eng);
else
puts("eh");
}
return 0;
}