poj 2503 Babelfish (map,trie 树)

链接:poj 2503

题意:输入 语言A及翻译为语言B的词典,之后再输入语言B的单词,判断是否能从词典中找到,

若能找到,将其翻译为语言A,否则输出“eh”.

思路:这题肯定得先将词典对应语言存起来,但是如果直接暴力找输入的单词是否出现过,必然会TLE

因为单词都是一对一的关系,可以用map实现

当然,trie树是用空间换时间,对于字符串的查找,在时间上有着相当的优势,因此也可以用trie树

注:sscanf函数从一个字符串中读进与指定格式相符的数据. 

map实现:938MS

#include<iostream>
#include<map>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
int main()
{
    map<string,string> word;
    map<string,string>::iterator i;
    char s[25],s1[15],s2[15];
    while(gets(s)!=NULL){
        if(strcmp(s,"")==0)
            break;
        sscanf(s,"%s %s",s1,s2);
        word[s2]=s1;
    }
    while(gets(s)!=NULL){
        if((i=word.find(s))!=word.end())
            cout<<i->second<<endl;
        else
            cout<<"eh"<<endl;
    }
    return 0;
}

trie 树实现:422MS

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct stu
{
    struct stu *next[26];           
    char s[12];
}node;
node* creat_node()           //创建新节点并初始化
{
    node *p=(node *)malloc(sizeof(node));
    memset(p->next,0,sizeof(p->next));
    return p;
}
void trie_insert(node *p,char *s,char *word)
{
    int i;
    while(*s!='\0'){
        i=*s-'a';
        if(p->next[i]==0)
            p->next[i]=creat_node();
        p=p->next[i];
        s++;
    }
    strcpy(p->s,word);         //将对应单词存起来
}
void trie_search(node *p,char *s)
{
    int i;
    while(*s!='\0'){
        i=*s-'a';
        p=p->next[i];
        if(p==0){
            printf("eh\n");
            return ;
        }
        s++;
    }
    printf("%s\n",p->s);
}
int main()
{
    node *root=NULL;
    char s[25],t[12],word[12];
    root=creat_node();
    while(gets(s)!=NULL){
        if(strcmp(s,"")==0)
            break;
        sscanf(s,"%s %s",word,t);
        trie_insert(root,t,word);
    }
    while(gets(s)!=NULL)
        trie_search(root,s);
    return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值