POJ 2503-Babelfish

来源:互联网 发布:js 转换json对象 编辑:程序博客网 时间:2024/06/17 19:59
Babelfish
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 46511 Accepted: 19518

题目链接:点击打开链接

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



题意:
给你几组单词,每组有两个单词,前一个单词是后一个单词的替换,然后以空行结束,再给你单词,如果可以被替换,就输出它的替换单词,否则就输出“eh”。

分析:
在学字典树,即使本题用map更简单,但是我还是大费周折的钻研字典树的写法,哎,就是因为使用 sscanf 时,里面多了个逗号,真是让我好找,哎,头都大了,说明对 sscanf 掌握的还不是很好,看代码吧。



#include<iostream>#include<stdio.h>#include <stdlib.h>#include<string>#include<string.h>using namespace std;const int INF=26;typedef struct Node{    bool end1;///单词的结束标志    char str[15];///存该单词的替换单词    struct Node *son[INF];///孩子}Tree;void Insert(Tree *root,char s2[],char s1[])///出入单词,建树{    Tree *p=root;    int k=0;    char c1=s2[k];    while(c1!='\0')    {        if(p->son[c1-'a']==NULL)        {            Tree *temp=new Tree;            for(int i=0;i<INF;i++)                temp->son[i]=NULL;            temp->end1=false;///不是单词的结束            p->son[c1-'a']=temp;            p=p->son[c1-'a'];        }        else            p=p->son[c1-'a'];        c1=s2[++k];    }    p->end1=true;///该单词的结束,将替换单词赋给该节点    strcpy(p->str,s1);}void Find(Tree *root,char s2[])///查找单词的替换单词{    int k=0;    char c1=s2[k];    Tree *p=root;    while(p!=NULL&&c1!='\0')    {        p=p->son[c1-'a'];        c1=s2[++k];    }    if(p==NULL)///说明没找到        printf("eh\n");    else if(p->end1==false)///没找到        printf("eh\n");    else        printf("%s\n",p->str);}void Free(Tree *root)///释放字典树{    for(int i=0;i<INF;i++)    {        if(root->son[i]!=NULL)            Free(root->son[i]);    }    free(root);}int main(){    char s[25],s1[15],s2[15];     Tree *root=new Tree;    for(int i=0;i<INF;i++)        root->son[i]=NULL;    while(gets(s))    {        if(strlen(s)==0)            break;///如果是空行,就跳出        sscanf(s,"%s %s",s1,s2);        Insert(root,s2,s1);    }    while(gets(s2))    {        Find(root,s2);    }    Free(root);    return 0;}





原创粉丝点击