HNUSTOJ-1253 Babelfish(字典树)

本文介绍了一个基于字典的翻译程序实现方法,利用前缀树数据结构存储单词映射,高效完成从一种语言到另一种语言的翻译任务。文章提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1253: Problem C: Babelfish

时间限制: 1 Sec  内存限制: 128 MB
提交: 14  解决: 3
[提交][状态][讨论版]

题目描述

 

Problem C: Babelfish

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 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 is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".

输入

 

输出

 

样例输入

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

样例输出

cat
eh
loops
#include<iostream>
#include<cstring>
#include<cstdio>
 
using namespace std;
const int N = 110000 + 5;
 
struct node{
    int v;
    struct node *next[26];
}*T;
 
node *newnode(){
     node *p = new node;
     for(int i = 0; i < 26; i++) p -> next[i] = NULL;
     return p;
}
 
void Insert(node *p, char *str, int v){
    int c, len = strlen(str);
    for(int i = 0; i < len; i++){
        if(!islower(str[i])) continue;
        c = str[i] - 'a';
        if(p -> next[c] == NULL) p -> next[c] = newnode();
        p = p -> next[c];
    }
    p -> v = v;
}
 
int Query(node *p, char *str){
    int c, len = strlen(str);
    for(int i = 0; i < len; i++){
        if(!islower(str[i])) continue;
        c = str[i] - 'a';
        if(p -> next[c] == NULL) return 0;
        p = p -> next[c];
    }
    return p -> v;
}
char dic[N][15], str[30];
int main(){
    int cur = 0;
    T = newnode();
    while( ++cur ){
        fgets(str, 30, stdin);
        if(isspace(str[0])) break;
        sscanf(str, "%s %s", dic[cur], str);
        Insert(T, str, cur);
    }
    while(fgets(str, 30, stdin) != NULL){
        if(isspace(str[0])) break;
        cur = Query(T, str);
        printf("%s\n", cur? dic[cur]: "eh");
    }
}

 

 

转载于:https://www.cnblogs.com/Pretty9/p/7406788.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值