题目大概:
输入一个一对一的字典,每行两个字符串,然后输入一个单词,输出翻译后的单词,如果字典中没有该单词,输出eh。
思路:
输入字典用sscanf()函数,分别放在一个结构体中,对结构体排序,然后运用二分查找寻找要翻译的单词。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <string.h>
using namespace std;
struct f
{
char s1[20],s2[20];
} a[100001];
int cmp(f a,f b)
{return strcmp(a.s2,b.s2)<0;
}
int main()
{int le;
le=0;
char b[50];
while(gets(b))
{
if(b[0]=='\0')break;
sscanf(b,"%s%s",a[le].s1,a[le].s2);
le++;
}
sort(a,a+le,cmp);
while(gets(b))
{
int l=0,r=le-1,k=1;
while(l<=r)
{
int mid=(l+r)/2;
if(strcmp(b,a[mid].s2)==0)
{printf("%s\n",a[mid].s1);k=0;break;}
else if(strcmp(b,a[mid].s2)<0)r=mid-1;
else l=mid+1;
}
if(k)
printf("eh\n");
}
return 0;
}