Babelfish

本文介绍了一道编程题目,该题目要求利用二分搜索和qsort算法来实现一个简单的翻译功能。输入包含一个由多达10万条词汇组成的字典以及待翻译的消息,每条字典项包括英语单词及其对应的外语单词。文章提供了完整的C语言代码示例,展示了如何通过排序和二分搜索的方法来查找和翻译外语词汇。

摘要生成于 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
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

这道题需要用到两个小知识点,qsort和简单二分。

另外,有一个小技巧,如何使用二分才能让每个字符串都能和所有字符转进行比较。

这里采用的是使用一个数组作为字符串的下标,对其进行qsort排(以字符串的降序),

从而记下每个字符串的排位序号,进行二分比较。

代码如下:

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
char s[100002][14];
char t[100003][14];
int a[100003];
char w[100003];
int cmp(const void *a,const void *b)
{
    return strcmp(t[*(int *)a],t[*(int *)b]);
}
int main()
{
    int l=0;
    while(gets(w)&&w[0]!='\0')
    {
        sscanf(w,"%s %s",s[l],t[l]);
        a[l]=l;
        l++;
    }
    qsort(a,l,sizeof(a[0]),cmp);
    while(gets(w))
    {
        int i=0;
        int j=l-1;
        int flag=0,mid;
        while(i<=j)
        {
            mid=(i+j)/2;
            int p=strcmp(w,t[a[mid]]);
            if(p>0)
                i=mid+1;
            else if(p<0)
                j=mid-1;
            else
            {
                flag=1;
                break;
            }
        }
        if(flag)
            printf("%s\n",s[a[mid]]);
        else
            printf("eh\n");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值