poj 2503 Babelfish(trie树)

来源:互联网 发布:mysql如何创建存储过程 编辑:程序博客网 时间:2024/06/04 18:17
Babelfish
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 32439 Accepted: 13954

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 ogdaycat atcaypig igpayfroot ootfrayloops oopslayatcayittenkayoopslay

Sample Output

catehloops

Hint

Huge input and output,scanf and printf are recommended.
#include <iostream>#include <cstdio>#include <cmath>#include <cstdlib>#include <cstring>#define N 26using namespace std;struct trie{    struct trie *next[N];    bool isword;    int num;}*head;char temp[11],ans[100010][11],in[11];struct trie* hiti(){    struct trie* node = (struct trie *)malloc(sizeof(struct trie));    node->num = -1;    node->isword = false;    memset(node->next , 0 , sizeof(node->next));       return node;} void great_tree(char *a,int cnt){    struct trie *p = head,*q = NULL;    int len = strlen(a);    for(int i=0;i<len;i++)    {        int id = a[i]-'a';        if(p->next[id]==NULL)        {            q = new (struct trie);            for(int j=0;j<N;j++)                q->next[j] = NULL;            q->isword = 0;            p->next[id] = q;        }        if(i==len-1)        {            p->next[id]->isword = 1;            p->next[id]->num = cnt;        }        p = p->next[id];    }}int find_tree(char a[]){    struct trie *p = head;    int len = strlen(a);    for(int i=0;i<len;i++)    {        int id = a[i]-'a';        if(p->next[id]==NULL)            return -1;        p = p->next[id];    }    if(p->isword)        return p->num;    else       return -1;}int main(){    int cnt=-1;    head = hiti();    while(1)    {        cnt++;        gets(temp);        if(temp[0]=='\0')            break;        sscanf(temp,"%[^ ]",ans[cnt]);        sscanf(temp,"%*s%s",in);        great_tree(in,cnt);    }    while(gets(temp)!=NULL)    {        int t = find_tree(temp);        if(t == -1)            cout << "eh"<< endl;        else            cout << ans[t] << endl;    }    return 0;}


0 0
原创粉丝点击