hdu 1305 Immediate Decodability (字典树入门)

http://acm.hdu.edu.cn/showproblem.php?pid=1305
题目大意:给你一系列字符串,以9位分割线,判断在某个集合里的字符串有没有作为其他字符串的前缀出现。
解题思路:典型的字典树的题,只需要在构造字典树的时候判断这个节点是否可以构成字符串,且为叶子结点。这里出现前缀有两种情况,一是这个字符串还没有插入完,但已经遇到被标记的字符,二是,这个字符串已经插入完,但它还有后继节点。
code:

#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

struct Trie
{
    int flag;
    struct Trie *next[2];
    Trie(){
        flag = 0;
        for(int i=0;i<2;i++)
            next[i] = NULL;
    }
};
int ans ;
Trie *root,*p,*temp;
bool insert(char str[])
{
    p = root;
    for(int i=0;i<strlen(str);i++)
    {
        if(p->next[str[i]-'0']!=NULL){
            p = p->next[str[i] -'0'];
            if(p->flag == 1||i == strlen(str)-1){
        ///p->flag == 1还没有插入完,已经遇到被标记的节点,i == strlen(str)-1表示已经插入完毕,但此节点还有后继节点,此时标记一下变量,直接结束
                ans = 0;
                break;
            }
        }
        else{
                temp = new Trie;
                p->next[str[i] - '0'] = temp;
                p = temp;
            }
    }
    p->flag = 1;
}
void del(Trie *root)
{
    for(int i=0;i<2;i++)
    {
        if(root->next[i]!=NULL)
            del(root->next[i]);
    }
    delete(root);
}
int main()
{
    int c = 0;ans = 1;
    char str[15];root = new Trie;
    while(~scanf("%s",str))
    {
        if(str[0]=='9')
        {
            if(ans)  printf("Set %d is immediately decodable\n",++c);
            else     printf("Set %d is not immediately decodable\n",++c);
            del(root);root = new Trie;
            ans = 1;
            continue;
        }
        if(!ans)continue;
        insert(str);
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值