POJ 2503 Babelfish

时间:2021-10-13 08:56:47

Babelfish
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 28766 Accepted: 12407

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

字典树变形。。。。贴贴小模板。。。

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int MAXN=1000000;

int tot,root,child[MAXN][26],flag[MAXN],cas=1;
char str[20],dict[100100][20];

void Init()
{
    memset(child[1],0,sizeof(child[1]));
    memset(flag,-1,sizeof(flag));
    flag[1]=0;
    root=tot=1;
}

void Insert(const char *str,int num)
{
    int* cur=&root;
    for(const char *p=str;*p;p++)
    {
        cur=&child[*cur][*p-'a'];
        if(*cur==0)
        {
            *cur=tot++;
            memset(child[tot],0,sizeof(child[tot]));
            flag[tot]=-1;
        }
    }
    flag[*cur]=num;
}

int Query(const char* str)
{
    int *cur=&root;
    for(const char* p=str;*p&&~*cur;p++)
    {
        cur=&child[*cur][*p-'a'];
    }
    if(*cur==0) return -1;
    return flag[*cur];
}

int main()
{
    Init(); cas=1; bool first=true;
    char sss[50];
    while(gets(sss))
    {
        int pos=-1,cnt1=0,cnt2=0;
        int len=strlen(sss);
        for(int i=0;i<len;i++)
        {
            if(sss==' ')
            {
                pos=i; break;
            }
        }
        if(pos!=-1)
        {
            for(int i=0;i<pos;i++)
            {
                dict[cas][cnt1++]=sss;
            }
            for(int i=pos+1;i<len;i++)
            {
                    str[cnt2++]=sss;
            }
            Insert(str,cas++);
        }
        else if(pos==-1)
        {
            if(first) {first=false; continue;}
            int t = Query(sss);
            if(t==-1)
                puts("eh");
            else printf("%s\n",dict[t]);
        }
    }
    return 0;
}

* This source code was highlighted by YcdoiT. ( style: Codeblocks )