[ACM] [算法基础] POJ 2503 在线翻译Babelfish(二分查找 字符串)

本文介绍了一个基于大型词典进行消息翻译的编程挑战。任务涉及读取成千上万条词汇对照记录,并利用这些记录将一种外语的消息翻译成英语。文章详细解释了输入格式、输出要求及具体的实现方法,包括使用结构体和排序函数来加速查找过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值