HDU - 1075What Are You Talking About(字典树)

看题点这里

题意

先给你一个“字典” 地球语和火星语一一对应,再给你几串火星语让你翻译,非英文字母不用翻译,字典中找不到的原样输出。

思路

按照火星文构造字典树,用flag表示一个单词的结束,并在那个节点上存入对应的地球语,最后就是查找字典树,flag为1则输出翻译后的单词。

AC代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;

struct node
{
    char trans[11];//存原文
    bool flag;
    node *next[26];
};

node* creat()
{
    node *p=new node;
    p->flag=0;
    for(int i=0; i<26; i++)
        p->next[i]=NULL;
    return p;
}

void Insert(node *root,char *s,char *ss)//s为火星文,ss为对应的地球语
{
    node *p=root;
    int n=strlen(s);
    for(int i=0; i<n; i++)
    {
        if(p->next[s[i]-'a']==NULL)
            p->next[s[i]-'a']=creat();
        p=p->next[s[i]-'a'];
    }
    p->flag=1;//表示到此节点为一完整单词,并保存相应原文。
    strcpy(p->trans,ss);
}

void Search(node *root,char *s)
{
    node *p=root;
    int n=strlen(s);
    int i;
    for(i=0; i<n; i++)
    {

        if(p->next[s[i]-'a']==NULL)
        {
            printf("%s",s);
            return;
        }
        p=p->next[s[i]-'a'];
    }
    if(p->flag==1)//能在树中找到单词,输出地球语
        printf("%s",p->trans);
    else//否则输出原文
        printf("%s",s);
}
int main()
{
    char s[30010],s2[11],s1[11];
    node *root=creat();
    while(~scanf("%s",s1)&&strcmp(s1,"END")!=0)
    {
        if(strcmp(s1,"START")==0)
            continue;
        scanf("%s",s2);
        Insert(root,s2,s1);
    }
    getchar();
    while(gets(s)&&strcmp(s,"END")!=0)
    {
        if(strcmp(s,"START")==0)
            continue;
        int n=strlen(s);
        for(int i=0; i<n; i++)
        {
            if(isalpha(s[i]))//此函数用于判断是否为英文字母,不是输出0
            {
                int t=0;
                memset(s1,'\0',sizeof(s1));
               while(isalpha(s[i]))
                 s1[t++]=s[i++];
               Search(root,s1);
            }
            if(!isalpha(s[i])) printf("%c",s[i]);
        }
        if(isalpha(s[n-1])) Search(root,s1);//最后一个别忘判断!
        printf("\n");
    }
    return 0;
}

后记

此题还有用map的做法,把火星文和地球语映射,这里不做讨论

猜你喜欢

转载自blog.csdn.net/Here_SDUT/article/details/105442031