HDU - 1305 Immediate Decodability 字典树

字典树:问是否在给出的二进制中能找到前缀码。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
	int x;
	node *next[22];
	node()
	{
		x=0;
		for(int i=0;i<2;i++)
		next[i]=NULL;
	}
};
node root;
bool update(char *s)
{
	int k1=0,k2=1;
	int l=strlen(s);
	int id=0;
	node *p=&root;
	for(int i=0;i<l;i++)
	{
		if(p->x==1)
		k2=0;
		id=s[i]-'0';
		if(p->next[id]==NULL)
		{
			k1=1;
			node *q=new node;
			p->next[id]=q;
		}
		p=p->next[id];
	}
	p->x=1;
	return k1&&k2;
}
int freedom(node *p)
{
	int i=0;
    for(i=0;i<2;i++)
    if(p->next[i]!=NULL) 
	freedom(p->next[i]);
    if(p==&root)
	{
    	for(int j=0;j<2;j++)
    		p->next[j]=NULL;
    	p->x=0;
	}
	else
	{
		delete(p);
	}
	return 0;
}
int main(void)
{
	int i,j,k=1,kk=1,t=1;
	char s[20];
	while(scanf("%s",s)!=EOF)
	{
		if(s[0]=='9')
		{
			if(kk==1)
			printf("Set %d is immediately decodable\n",t++);
			else
			printf("Set %d is not immediately decodable\n",t++);
			k=1;
			kk=1;
			freedom(&root);
		}
		else
		{
			k=update(s);
			if(k==0)
			kk=0;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值