hdu1075(字典树)

What Are You Talking About

题意:

  给出Martian的语言的单词对应的英语单词以及一段用Martian的语言写成的文本,现在要求把文本翻译成英文,文本中的空格,换行,‘\t’以及标点符号不用翻译,如果某个单词没给出对应的英语单词,那么它也不用翻译。

分析:

  用给出的Martian单词建立,在单词结尾对应的节点存下对应的英语单词,注意一定要开一个标记代表这里是单词的结尾,因为可能存在一个单词是另一个单词前缀的情况,在这里RE了很多次(代码结束给出了我RE的数据)。

代码:

#include <map>
#include <queue>
#include <math.h>
#include <string>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;
#define ll long long
#define ull unsigned long long
#define cls(x) memset(x,0,sizeof(x))
#define clslow(x) memset(x,-1,sizeof(x))

const int maxn=1e4;
const int wordLen=30;

char line[maxn];

struct TrieNode {
    char* s;
    bool isword;
    TrieNode* nex[26];
};
TrieNode* root;

TrieNode* build()
{
    TrieNode* node=new TrieNode;
    node->isword=false;
    cls(node->nex);
    return node;
}

void Insert(char* s,char* code)
{
    int len=strlen(s);
    TrieNode* node=root;
    for(int i=0;i<len;i++){
        int x=s[i]-'a';
        if(node->nex[x]==NULL){
            node->nex[x]=build();
        }
        node=node->nex[x];
    }
    node->isword=true;
    node->s=new char[strlen(code)];
    strcpy(node->s,code);
}

char* decode(char* s)
{
    int len=strlen(s);
    TrieNode* node=root;
    for(int i=0;i<len;i++){
        int x=s[i]-'a';
        if(node->nex[x]==NULL){
            return s;
        }
        node=node->nex[x];
    }
    if(node->isword)    return node->s;
    return s;
}

void del(TrieNode* node)
{
    for(int i=0;i<26;i++){
        if(node->nex[i]!=NULL){
            del(node->nex[i]);
        }
    }
    free(node);
}

int main()
{
//    freopen("in.txt","r",stdin);
    root=build();
    char s1[wordLen],s2[wordLen];
    while(scanf("%s",s1)!=EOF)
    {
        if(strcmp(s1,"START")==0)  continue;
        else if(strcmp(s1,"END")==0)    break;
        scanf("%s",s2);
        Insert(s2,s1);
    }

    getchar();
    char word[wordLen];
    while(gets(line))
    {
        if(strcmp(line,"START")==0)  continue;
        else if(strcmp(line,"END")==0)    break;

        int cnt=0,len=strlen(line);
        for(int i=0;i<len;i++){
            if('a'<=line[i]&&line[i]<='z'){
                word[cnt++]=line[i];
                word[cnt]='\0';
            }
            else{
                if(cnt)    printf("%s",decode(word));
                printf("%c",line[i]);
                cnt=0;
            }
        }
        if(cnt) printf("%s",decode(word));
        printf("\n");
    }
    return 0;
}

/**
START
from fiwo
hello difh
trap dif
mars riwosf
earth fnnvk
like fiiwj
END
START
difh, i'm fiwo riwosf.
i fiiwj fnnvk! dif fnn f
END
**/
View Code

 

posted on 2018-08-01 08:40  我过了样例耶  阅读(235)  评论(0编辑  收藏  举报

导航