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 Hint
Huge input and output,scanf and printf are recommended.
Source |
思路先sort,在二分
注意因为要以空行为结尾,所以必须以gets()的形式,输入。
然后判断str1[0] == ’\0'代表判断是否为空行。
那么这里就要会用sscanf(str,"%s%s",a[i].data,a[i].trans)来还原不为空行的前提下的原字符串。
还有就是不知为毛C++提交是WA,但G++提交AC,一开始蒙了,大神表示看多了,给我改成G++,AC了,玄学!
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int cnt;
struct node
{
char data[20],trans[20];
}a[100010];
bool cmp(node a,node b)
{
return strcmp(a.trans,b.trans)<0;
}
void read()
{
char str1[50];
cnt = 0;
while(gets(str1))
{
if(str1[0] == '\0')
break;
sscanf(str1,"%s%s",a[cnt].data,a[cnt].trans);
cnt++;
}
}
void cha(int l,int r,char str[])
{
int i,j,m;
i = l;
j = r;
if(l <= r)
{
m = (i+j)/2;
if(strcmp(a[m].trans,str) == 0)
printf("%s\n",a[m].data);
else if(strcmp(a[m].trans,str) < 0)
cha(m+1,r,str);
else
cha(l,m-1,str);
}
else
printf("eh\n");
}
int main()
{
read();
sort(a,a+cnt,cmp);
char str[50];
while(gets(str))
{
cha(0,cnt-1,str);
}
return 0;
}