HDU1075

复习种Trie树了


最后那个句子分割的时候不好弄,其他的基本就是模板了

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

const int CHILD_NUM = 26;
const int BASE = 'a';
struct Node
{
    Node * child[CHILD_NUM];
    char * str;
    Node()
    {
        memset(child,0,sizeof(child));
        str = 0;
    }
    ~Node()
    {
        for(int i = 0; i < CHILD_NUM; i++)
            if(child[i])
                delete child[i];
        if(str)
            delete []str;//对于基本类型,写不写一样
    }

};

struct Trie
{
    Node * root;
    Trie()
    {
        root = new Node();
    }
    ~Trie()
    {
        if(root)
            delete root;
    }
    void Insert(char * str,char* content)
    {
        int len = strlen(content);
        Node * cur = root;
        int i = 0;
        while(str[i])
        {
            const int &index = str[i] - BASE;
            if(cur->child[index]==NULL)
                cur->child[index] = new Node();
            cur = cur->child[index];
            i++;
        }
        cur->str = new char[len+1];
        strcpy(cur->str,content);
    }

    char * Search(char * str)//返回与str匹配的字符串,没有返回0
    {
        Node * cur = root;
        int i = 0;
        while(str[i])
        {
            //cout << "str[i] = " << str[i] << endl;
            const int& index = str[i] - BASE;
            if(cur->child[index])
                cur = cur->child[index];
            else
                return NULL;
            i++;
        }
        return cur->str;
    }

};

char str[3010];

int main()
{
    char word1[15],word2[15];
    scanf("%s",&word1);
    Trie tree;
    while(~scanf("%s%s",word1,word2)&& strcmp(word1,"END")!=0)
    {
        tree.Insert(word2,word1);
    }
    //START已被读过
    getchar();//读取换行符
    char tmp[50];
    int cnt;
    char * res;
    while(gets(str) && strcmp(str,"END")!=0)
    {
        //cout << "str = " << str << endl;
        int i = 0;
        cnt = 0;
        while(str[i])
        {
            if(islower(str[i]))
            {
                tmp[cnt++] = str[i];
            }
            else
            {
                if(cnt > 0)
                {
                    tmp[cnt++] = '\0';
                    cnt = 0;
                    res = tree.Search(tmp);
                    if(res)
                        printf("%s",res);
                    else
                        printf("%s",tmp);
                }
                putchar(str[i]);
            }
            i++;
        }
        putchar('\n');
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值