百练2503在线翻译题解

2503:Babelfish

总时间限制: 

3000ms

 

内存限制: 

65536kB

描述

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 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 is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".

样例输入

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

样例输出

cat
eh
loops

提示

Huge input and output,scanf and printf are recommended.

来源

Waterloo local 2001.09.22

 

 

本题涉及大量的数据的查找,同时是字符串的处理

先对数据进行排序,考虑到是字典目用sort的自定义排序

利用strcmp返回值进行二分搜索

#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

struct Entry 
{
	char english[11];
	char foreign[11]; 
}entries[100005];
/*定义字典条目*/
int Cmp(Entry e1,Entry e2)
{
	return strcmp(e1.foreign,e2.foreign)>0;
}
int main()
{
	int n=0;
	while(1)
	{
		scanf("%s%s",entries[n].english,entries[n].foreign);
		n++;
		//cin.get();
		getchar(); 
		if(cin.peek()=='\n') break;
	}
	sort(entries,entries+n,Cmp);
	char word[11];
	while(scanf("%s",word)!=EOF)
	{
		int left=0,right=n-1;
		int f=0;
		while(left<=right)
		{
			int mid=left+(right-left)/2;
			f=strcmp(entries[mid].foreign,word);
			if(f>0) left=mid+1;
			else if(f<0) right=mid-1;
			else{
				printf("%s\n",entries[mid].english);
				break;
			} 
		}
		if(f) printf("eh\n");
	}
	return 0;
} 

简单介绍scanf()函数的原理

 

想象输入设备(键盘)连接着一个叫“缓冲”的东西,把缓冲认为是一个字符数组。
当你的程序执行到scanf时,会从你的缓冲区读东西,如果缓冲区是空的,就阻塞住,等待你从键盘输入。
现在假设你的缓冲区里有:abcd\n1234\n  (其中\n是回车符)执行:scanf("%s",name);的时候,由于scanf是读数据直到看见空白符(空白符:指空格符、制表符、回车符)就停止的输入函数。所以执行后,把abcd存到了name中。缓冲区于是变成了 : \n1234\n

所以在读入字典目之后 需要判断的是 空行

首先需要把scanf没有读入的那个'\n'清除掉 (cin.get();getchar())均可

然后用cin.peek();读取到接下来的第一个字符  这个操作是读 不会把字符取出

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值