POJ-2503 Babelfish 解题报告

Description

You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.

Input

Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.

Output

Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".

Sample Input

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

Sample Output

cat
eh
loops
题目大意:给你一本字典,左边是英文,右边是火星文(这是我这么说的。。),然后输入火星文,是否能找到相应的翻译,有则输出翻译,无则输出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;
}

当然因为初学这些函数,有什么不对的地方敬请指教。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值