HDU 1305

这道题是字典树入门题目,今天下午刚学字典树,理解了原理,然后看看代码就会发现简单了!
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef struct trie
{
    int v;
    trie *next[2];


}trie;


trie *root;




void creattrie(char *str)
{
    int i,j;
    trie *p=root,*q;
    int len=strlen(str);
    for(i=0; i<len; i++)
    {
        int id=str[i]-'0';
        if(p->next[id]==NULL)
        {
            q=(trie *)malloc(sizeof(trie));
            q->v=1;
            for(j=0; j<2; j++)
            {
                q->next[j]=NULL;
            }
            p->next[id]=q;
            p=p->next[id];
        }
        else
        {
            p->next[id]->v++;
            p=p->next[id];
        }
    }
}


int findtrie(char *str)
{
    int len,i;
    len=strlen(str);
    trie *p=root;
    for(i=0; i<len; i++)
    {
        int id=str[i]-'0';
        p=p->next[id];
        if(p==NULL)
            return 0;
    }
    return p->v;
}




int main()
{
    char str[10][20];
    int tcase=0;
    int i;
    while(scanf("%s",str[0])!=EOF)
    {
        root=(trie *)malloc(sizeof(trie));
        for(i=0; i<2; i++)
            root->next[i]=NULL;
        int k=1;
        creattrie(str[0]);
        while(scanf("%s",str[k])!=EOF&&str[k][0]!='9')
        {
            creattrie(str[k++]);
        }
        for(i=0; i<k; i++)
        {
            int flag;
            flag=findtrie(str[i]);
            if(flag>1)//一开始这里错了,就是flag一定要大于1,因为它本身就是一个!
            {
                printf("Set %d is not immediately decodable\n",++tcase);
                break;
            }
        }
        if(i>=k)
        {
            printf("Set %d is immediately decodable\n",++tcase);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值