poj2503 二分查找

题意是:给出单词并给出其对应的方言单词,各单词总数不超过100000个,两个单词之间用空格隔开,将对应的单词输入完之后,空一行,输入方言单词,对应输出翻译的英文单词,若没有,则输出'eh'。

本题先将有对应英文翻译的方言单词从小到大排序,运用二分查找,找到输入的待翻译的方言单词,输出对应的翻译的英文单词。

本题的难点在于对输入的实现,我们通过对空格的判断来控制输入,具体代码实现如下:

C语言:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node{
char foreign[11];
int number;
};
node f[100001];
char uniform[100001][11];
char temp[11];
bool cmp(node a,node b)
{
if(strcmp(a.foreign,b.foreign)<0)
return true;
else
return false;
}
int main()
{
int n=0;
char c;
scanf("%s",uniform[n]);
scanf("%c",&c);
while(c==' ')
{
scanf("%s",f[n].foreign);
f[n].number=n;
n++;
scanf("%s",uniform[n]);
scanf("%c",&c);
}
strcpy(temp,uniform[n]);
sort(f,f+n,cmp);
int low,high,mid;
do
{

low=0;
high=n-1;
while(low<high)
{
mid=(low+high)/2;
if(strcmp(temp,f[mid].foreign)==0) break;
else if(strcmp(temp,f[mid].foreign)<0) high=mid;
else low=mid+1;
}
if(low==high)
{
if(strcmp(temp,f[low].foreign)==0) printf("%s\n",uniform[f[low].number]);
else
printf("eh\n");
}
else printf("%s\n",uniform[f[mid].number]);
} while(scanf("%s",temp)!=EOF);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值