描述
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
解法
建立对字符串的结构体 cmp函数排序(strcmp(a,b))
cin.peek()探查输入流中的下一个字符 使用前用cin.get()将每个词条的换行符处理掉
代码
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
struct Entry
{
char ENG[11];//English
char FOG[11];//外语Foreign
}entry1[100005];
int Cmp(Entry a,Entry b)
{
return strcmp(a.FOG,b.FOG)<0;
}
void binarySearch(Entry entry1[100005],int n,char word[])
{
int mid,L=0,R=n-1;
int f=0;
while(R>=L)
{
mid=L+(R-L)/2;
f=strcmp(entry1[mid].FOG,word);
if(f<0)
L=mid+1;
else if(f>0)
R=mid-1;
else if(f==0)
{
printf("%s\n",entry1[mid].ENG);
break;
}
}
if(f!=0) printf("eh\n");
}
int main()
{
//freopen("Text.txt","r",stdin);
int n=0;
while(1)
{
scanf("%s%s",entry1[n].ENG,entry1[n].FOG);
n++;
cin.get();
if(cin.peek()=='\n') break;
}
sort(entry1,entry1+n,Cmp);
char word[11];
while(~scanf("%s",word))
{
binarySearch(entry1,n,word);
}
return 0;
}