Babelfish

来源:互联网 发布:js math方法 编辑:程序博客网 时间:2024/06/05 00:17
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 ogdaycat atcaypig igpayfroot ootfrayloops oopslayatcayittenkayoopslay
Sample Output
cateh

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");    }}


0 0
原创粉丝点击