hdu1075What Are You Talking About(Trie tree)

来源:互联网 发布:注册域名需要哪些手续 编辑:程序博客网 时间:2024/05/15 08:38

晚上A一题,睡的香~@Albafica大牛

睡觉前再水一发字典树:

->题目请戳这里<-

题目大意:有个火星人,写了一段火星文,都看不懂,但是留下了一本字典,要求翻译。能翻译的翻译,不能翻译的直译~

题目分析:字典树字典树~

详情请见代码:

#include <iostream>#include<cstdio>#include<cstdlib>#include<cstring>using namespace std;typedef struct node{    struct node *next[26];    char s[11];    bool tag;}tree;char s1[3001],s2[3001];void init(tree *t){    memset(t->s,0,sizeof(t->s));    for(int i = 0;i < 26;i ++)        t->next[i] = NULL;    t->tag = 0;}void build(tree *t,int id){    if(t->next[s2[id] - 'a'] == NULL)    {        t->next[s2[id] - 'a'] = (tree *)malloc(sizeof(tree));        init(t->next[s2[id] - 'a']);    }    if(s2[id + 1])        build(t->next[s2[id] - 'a'],id + 1);    else    {        strcpy(t->next[s2[id] - 'a']->s,s1);        t->next[s2[id] - 'a']->tag = 1;    }}int find(tree *t,int id){    if(t->next[s2[id] - 'a'] == NULL)        return 0;    if(s2[id + 1] == '\0')//到了查找的单词末尾    {        if(t->next[s2[id] - 'a']->tag)//如果字典中也查到了末尾,即查到        {            printf("%s",t->next[s2[id] - 'a']->s);            return 1;        }        return 0;//要查找的单词短了,即没找到    }    return find(t->next[s2[id] - 'a'],id + 1);}int main(){    int i,j;    tree *root = NULL;    scanf("%s",s1);    root = (tree *)malloc(sizeof(tree));    init(root);    while(scanf("%s",s1),strcmp(s1,"END") != 0)    {        s1[strlen(s1)] = '\0';        scanf("%s",s2);        s2[strlen(s2)] = '\0';        build(root,0);    }    //scanf("%s",s1);    gets(s1);    gets(s1);    //printf("s1:%s\n",s1);    while(gets(s1),strcmp(s1,"END") != 0)    {        //printf("s11:%s\n",s1);        for(i = 0;s1[i];i ++)        {            if(!islower(s1[i]))                putchar(s1[i]);            else            {                j = 0;                while(islower(s1[i]))                    s2[j ++] = s1[i ++];                i --;                s2[j] = '\0';                if(!find(root,0))                    printf("%s",s2);                j = 0;            }        }        printf("\n");    }    return 0;}//468MS59932K


原创粉丝点击