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();读取到接下来的第一个字符 这个操作是读 不会把字符取出