hdu1075What Are You Talking About(字典树)

题目链接:hdu1075

/*hdu 1075 What Are You Talking About(字典树)
题目大意:
    每行输入两个单词,第二个单词可以翻译成第一个单词。
给出一串字符,能翻译的输出翻译后的单词,不能的原样输出。

思路:字典树

*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
bool flag;
struct node
{
    bool flag;
    char str[15];
    node *next[26];
}*root;
node *build()//建立结点
{
    node *p = (node *)malloc(sizeof(node));
    for(int i = 0; i < 26; i ++)
        p -> next[i] = NULL;
    p -> flag = false;
    return p;
}
void save(char *a, char *s)
{
    int len = strlen(s);
    node *p;
    p = root;
    for(int i = 0; i < len; i ++)
    {
        if(p -> next[s[i] - 'a'] == NULL)
            p -> next[s[i] - 'a'] = build();
        p = p -> next[s[i] - 'a'];
    }
    p -> flag = true;//标记,单词的最后一个字符
    strcpy(p -> str, a);//在该结点将翻译后的单词存下

}
void query(char *s)
{
    int len = strlen(s);
    node *p;
    p = root;
    for(int i = 0; i < len; i ++)
    {
        if(p -> next[s[i] - 'a'] == NULL)
        {
            printf("%s",s);
            return;
        }
        p = p -> next[s[i] - 'a'];
    }
    if(p -> flag)//单词能被翻译
        printf("%s", p -> str);
    else
        printf("%s", s);
}
int main()
{
   char s1[15],s2[15],ss[3005];
   scanf("%s",s1);
   root = build();
   while(scanf("%s",s1), strcmp(s1, "END"))
   {
       scanf("%s",s2);
       save(s1, s2);
   }
   scanf("%s",s1);
   getchar();
   while(gets(ss), strcmp(ss, "END"))
   {
       int len = strlen(ss);
       for(int i = 0; i < len; i ++)
       {
           if(islower(ss[i]))
           {
               int j = 0;
               memset(s1, '\0', sizeof(s1));
               while(islower(ss[i]))
                    s1[j++] = ss[i++];
               query(s1);
           }
           if(!islower(ss[i])) printf("%c",ss[i]);
       }
       if(islower(ss[len-1])) query(s1);
       printf("\n");
   }
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值