赫夫曼编码(从根结点开始编码)

/**
*2018.09.18 14:09
*赫夫曼编码(从根结点开始编码)
*/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>


typedef struct HuffmanTree {
	int weight;
	int parent, lchild, rchild;
}HuffmanTree;


char**  huffmanCoding(int *w, int n);
void getMins(HuffmanTree *tree, int rear, int *min1, int *min2);


int main(void) {
	int w[] = {1000, 5000,2, 1, 3, 1, 8, 9, 66 , 365 ,987};
	char **hc = huffmanCoding(w, sizeof(w)/sizeof(int));

	for (int i = 0; i < sizeof(w) / sizeof(int); ++i)
		puts(hc[i]);
	
	free(hc);
	putchar('\n');
	system("pause");
	return 0;
}

char** huffmanCoding(int *w, int n){

	int s = 2 * n - 1;
	HuffmanTree *ht = (HuffmanTree *)malloc(s * sizeof(HuffmanTree));

	int i = 0;
	for (i; i < n; ++i, ++w) 
		ht[i] = (HuffmanTree) {*w, -1, -1, -1};
	for (i; i < s;++i) 
		ht[i] = (HuffmanTree) { -1, -1, -1, -1 };

	int min1, min2;
	for (i = n; i < s; ++i) {
		getMins(ht, i, &min1, &min2);

		ht[i].lchild = min1;
		ht[i].rchild = min2;
		ht[i].weight = ht[min1].weight + ht[min2].weight;
		ht[min1].parent = i;
		ht[min2].parent = i;
	}

	char **huffmanCode = (char **)malloc(n * sizeof(char *));
	char *temp = (char *)malloc(n * sizeof(char));
	
	//此时赫夫曼树已经构建完成,权重已无用处
	//因此可用weight作为标记位
	//为0表示进入其右结点(左结点),为1进入其左结点(右结点),为2表示回退到父结点
	for (i = 0; i < s; ++i)
		ht[i].weight = 0;
	int p = s - 1, len = 0;
	while (-1 != p) {
		if (0 == ht[p].weight) {
			ht[p].weight = 1;
			if (-1 != ht[p].rchild) {
				temp[len++] = '1';
				p = ht[p].rchild;
			}
			else {
				temp[len] = '\0';
				huffmanCode[p] = (char *)malloc((len + 1) * sizeof(char*));
				strcpy(huffmanCode[p], temp);
			}
		}
		else if (1 == ht[p].weight) {
			ht[p].weight = 2;
			if (-1 != ht[p].lchild) {
				temp[len++] = '0';
				p = ht[p].lchild;
			}
		}
		else {
			ht[p].weight = 0;
			p = ht[p].parent;
			--len;
		}
	}

	free(ht);
	free(temp);

	return huffmanCode;
}

void getMins(HuffmanTree *ht, int rear, int *min1, int *min2) {
	int i = 0;
	*min1 = *min2 = -1;
	for (i; i < rear; ++i) {
		if (-1 != *min1 && -1 != *min2)
			break;
		if (-1 == ht[i].parent)
			if (-1 == *min1)
				*min1 = i;
			else *min2 = i;
	}
	for (i; i < rear; ++i) {
		if (-1 == ht[i].parent && (ht[i].weight < ht[*min1].weight || ht[i].weight < ht[*min2].weight)) {
			if (ht[*min1].weight < ht[*min2].weight)
				*min2 = i;
			else *min1 = i;
		}
	}	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值