ZOJ1808 POJ1056 HDU1305 Immediate Decodability,Trie树

本文介绍了一种使用Trie树结构来判断一组编码是否立即可解码的方法,并提供了一个C++实现示例。通过构建Trie树并检查节点状态,可以有效地验证给定的编码集合是否满足立即可解码条件。

标准的Trie树的题,有个小错误一直弄了很久,还是不熟练啊


/*******************************************************************************
 # Author : Neo Fung
 # Email : neosfung@gmail.com
 # Last modified: 2011-10-04 19:17
 # Filename: ZOJ1808 POJ1056 HDU1305 Immediate Decodability.cpp
 # Description : 
 ******************************************************************************/
//  #include "stdafx.h"
//  #define DEBUG

#include <fstream>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <memory.h>
using namespace std;
#define KINDNUM 2
#define MAX	20000

struct TrieNode
{
	bool isNum;
	TrieNode *next[KINDNUM];
}node[MAX],*head;
int nodeInd;

bool insert(TrieNode *&root,char *num)
{
	TrieNode *location=root;
	int i=0,branch=0;
	if(location==NULL)
	{
		location=&node[nodeInd++];
		location->isNum=false;
		for (int j=0;j<KINDNUM;++j)
			location->next[j]=NULL;
		root=location;
	}

	while(num[i])
	{
		branch=num[i]-'0';
		if(location->next[branch] &&
				(!num[i+1] || location->next[branch]->isNum))
			return false;
		else if(!(location->next[branch]))
		{
			location->next[branch]=&node[nodeInd++];
			location->next[branch]->isNum=false;
			for (int j=0;j<KINDNUM;++j)
				location->next[branch]->next[j]=NULL;
		}
		++i;
		location=location->next[branch];
		if(!num[i])
			location->isNum=true;
	}
	return true;
}

int main(void)
{
#ifdef DEBUG  
	freopen("data.txt","r",stdin);  
#endif  
	char str[15];
	int ncase=1;
	while(gets(str) && strlen(str)!=0)
	{
		nodeInd=0;
		head=NULL;
		if(str[0]=='9') break;
		printf("Set %d ",ncase++);
		bool ans=insert(head,str);
		while(gets(str) && str[0]!='9')
		{
			if(ans)
				ans= ans&&insert(head,str);
		}
		if(ans)
			printf("is immediately decodable\n");
		else
			printf("is not immediately decodable\n");
	}

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值