Language of FatMouse

来源:互联网 发布:seo怎么学 编辑:程序博客网 时间:2024/05/13 15:24

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=109

大意就是因为China要加入WTO了,所以,fatmouse需要学下英语的说,然后你需要搞一个程序,让他能方便快捷的把 fat mouse 的语言翻译成英语,如果没有的话 输出 eh

最容易想到的就是暴力,时间复杂度为 O( n2 )  有超时的危险,然后,C++的STL 的map 给我们提供了一个很好的方法,但是效率相对较慢,但是随着竞赛水平的发展,纯模板能过的题越来越越少,所以 继续想下去,发现 Trip tree 是一个不错的方法,裸敲容易出错,在竞赛中如果没有模板的话,不建议搞。然后,继续思考,发现如果先对其排序,然后用二分的思想对其进行Search的话,效率也不错。故代码如下:


/*#include<iostream>#include<map>using namespace std;int main(){    map<string,string> entry;    char line[30];    char english[12],mouse[12];    string value,key;    map<string,string>::iterator location,pos;    while(gets(line)){        if(strlen(line) == 0)break;        sscanf(line,"%s%s",english,mouse);        key = mouse;        value = english;        entry[key] = value;    }    while(cin>>line){        location = entry.find(line);        if(location != entry.end())cout<<entry[line]<<endl;        else cout<<"eh\n";    }    return 0;}*/#include<stdio.h>#include<string.h>#include<stdlib.h>struct node{     char word[12],mouWord[12];}mouse[100006];int cmp(const void *a,const void *b){    struct node *ta = (struct node *)a;    struct node *tb = (struct node *)b;    return strcmp(ta->mouWord,tb->mouWord);}int BinSearch(int n, char *line){    int left = 0,right = n,mid;    while(left < right ){          mid = (left + right) / 2;          if(strcmp(mouse[mid].mouWord ,line) == 0) return mid;          else if(strcmp(mouse[mid].mouWord ,line) >  0)right = mid;          else left = mid + 1;    }    return -1;}int main(){    int n =0,pos;    char line[30];    while(gets(line)){         if(strlen(line) == 0)break;         sscanf(line,"%s%s",mouse[n].word,mouse[n].mouWord);         n++;               }    qsort(mouse,n,sizeof(mouse[0]),cmp);    while(gets(line)){        pos = BinSearch(n,line);        if(pos == -1)puts("eh");         else puts(mouse[pos].word);               }    return 0;}


原创粉丝点击