POJ - 2503 Babelfish 字典树做法

本文探讨了字典树在翻译应用中的实现,通过输入字典和外语文本,输出对应的英文翻译,对于处理不同方言的翻译具有较高效率。
Time Limit: 3000MS Memory Limit: 65536KB 64bit IO Format: %I64d & %I64u

[]   [Go Back]   [Status]  

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









字典树的简单题,上次这个题是用map做的,这次用来熟悉一下字典树。代码如下:
//还是老办法,不懂的地方手动画个字典树看看就知道了
#include <iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
const int maxn=200000+5;//结点数应该不会超过100000*2,不要问我为什么,我也不知道。也许可以证明一下???
int ch[maxn][26];//a~z对应0~25,势必有一些空间是浪费的,这就是字典树的特点之一:用空间换时间
char s[25],a[11],b[11];
char save[maxn][11];//维护一个save数组,存储单词结尾信息。如果save非空,说明是单词结尾
int tp;//结点编号
void insert(char *x,int site)
{
    if(*x)//如果还没读到字符串的结尾
    {
        if(!ch[site][*x-'a'])//如果没有公共前缀(即前缀不存在或为空)
        ch[site][*x-'a']=++tp;//建立新的结点(如果前缀存在,则不进行)
        insert(x+1,ch[site][*x-'a']);
    }
    else strcpy(save[site],a);//在字符串末尾附加save数组,表示单词结尾
}




void query(char *x,int site)//查询按照插入的理解就可以
{
    if(*x)
    {
        if(!ch[site][*x-'a'])
        printf("eh\n");
        else
        query(x+1,ch[site][*x-'a']);
    }
    else
    printf("%s\n",save[site]);


}
int main()
{
    tp=0;
    while(1)//记住这种读取字符串的处理方式
    {
        gets(s);
        if(s[0]=='\n'||s[0]=='\0') break;
        sscanf(s,"%s%s",a,b);
        insert(b,0);
    }
    while(scanf("%s",a)!=EOF)
    {
        query(a,0);
    }
    return 0;
}







总结:字典树开始还是有点难理解的,虽然好像没有线段树那么坑。。。这个可作为模板使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值