您的位置:首页 > 其它

poj 2503 Babelfish(广义索引类线性表:快排+二分)

2014-07-20 15:58 344 查看
Babelfish

点击打开链接

Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 31543Accepted: 13583
Description
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

Hint
Huge input and output,scanf and printf are recommended.
Source
Waterloo local 2001.09.22

题意:先输入多行english字和foreign字,它们中间用空格隔开,

输入一个空行后,再输入要查询的foreign字,输出其对应的english字即可;

1:解决输入问题,如何实现以空行结束;



通过gets输入一行再判断是否为空行(gets函数是以回车为结束的,不能输入回车所以可用是s[0]!='\0'作为判断);

2:查找;

使用的二分查找(因为题目给的数据量比较大,这样避免超时)

在二分查找的时候注意判断条件要全,否则会出问题;

第一次使用的二分如下:



结果就TLE了,

然后改成这个样子就对了:



╮(╯▽╰)╭,细心啊!!

代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 100000
struct dictionary
{
    char english[12];
    char foreign[12];
} d[MAX];
char s[2*MAX];
int cmp(const void *a,const void *b)
{
    dictionary *p=(dictionary *)a,*p1=(dictionary *)b;
    return strcmp(p->foreign,p1->foreign);
}
int findstring(int start,int e,char s[])//二分查找
{
    if(strcmp(d[(start+e)/2].foreign,s)==0)
        return (start+e)/2;
    else if((start==e))
        return -1;
    else if(strcmp(d[(start+e)/2].foreign,s)<0)
    {
        return findstring((start+e)/2+1,e,s);
    }
    else
        return findstring(start,(start+e)/2-1,s);
    return -1;
}
int main()
{
    int num=0,k;
    gets(s);
    while(s[0]!='\0')//输入字典
    {
        sscanf(s,"%s%s",d[num].english,d[num].foreign);
        num++;
        gets(s);
    }
    qsort(d,num,sizeof(d[0]),cmp);//把foreign按字典序排列起来
    while(~scanf("%s",s))//输入查询的词
    {
        k=findstring(0,num-1,s);
        if(k<0)
            printf("eh\n");
        else
            printf("%s\n",d[k].english);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: