poj 2503 Babelfish (map / 二分)

题目:http://poj.org/problem?id=2503

Sample Input

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

Sample Output

cat
eh
loops
题意:

字典里每行两个单词,第一个为解释,第二个为原词,两词之间用空格隔开,单词均不重复出现,输入一 个空行,再输入一系列原词,输出原词的翻译,若字典里没有相关翻译,则输出“en”.

遇到的问题:判断某原词的解译词为空;用printf()输出时报错。用map太慢。

#include<stdio.h>
#include<queue>
#include<map>
#include<iostream>
using namespace std;
int main()
{
    char a[25],b[14],c[15];
    map<string ,string > mes;
    while(gets(a)&&a[0]!=0)
    {
        sscanf(a,"%s%s",b,c);
        mes[c]=b;
    }
    while(gets(a)&&a[0]!=0)
    {
        if(mes[a][0]=='\0')printf("eh\n");
        else printf("%s\n",mes[a].c_str());//cout<<mes[a]<<endl;
    }
    return 0;
}

用二分要明显快一些;

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<iostream>
using namespace std;
const int maxn=100009;
struct word
{
    char a[12],b[12];
}entry[maxn];
int n;
int cmp(word A,word B)
{
    if(strcmp(A.b,B.b)<0)return 1;
    return 0;
}
int main()
{
    char c[23];
    n=0;
    while(gets(c))
    {
        if(c[0]==0)break;
        sscanf(c,"%s%s",entry[n].a,entry[n].b);
        n++;
    }
    sort(entry,entry+n,cmp);
    while(gets(c))
    {
      int l=0,r=n-1,mid,t;
      while(l<=r)
      {

          mid=(l+r)>>1;
          t=strcmp(c,entry[mid].b);
          if(t==0)break;
          else
          {
              if(t>0)l=mid+1;
              else r=mid-1;
          }
      }
      if(t==0)printf("%s\n",entry[mid].a);
      else printf("eh\n");
    }
    return 0;
}

还可用hash算法解决http://yzmduncan.iteye.com/blog/883843


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值