DSOJ Huffman coding tree(Huffman编码树)

题目链接

#include<stdio.h>		//Huffman coding tree
#include<string.h>
#include<stdlib.h>
#define MAX 200			//The maximum number of node

typedef struct node
{
	int weight;
	int parent, lchild, rchild;
	int flag;
}HT;

void initial(HT *TREE,int n)		//Initialize the information of the node
{
	int i = 1;
	for (; i <= n; i++)
	{
		TREE[i].parent = 0;
		TREE[i].lchild = 0;
		TREE[i].rchild = 0;
		TREE[i].flag = 0;
	}
}

void select_min(HT *TREE, int n, int *s1, int *s2)		//Select two nodes with the minimum weight whose flag is 0
{
	int i;
	for (i = 1; i <= n; i++)
	{
		if (TREE[i].flag == 0)
		{
			*s1 = i;
			break;
		}
	}
	for (i = (*s1) + 1; i <= n; i++)
	{
		if (TREE[i].flag == 0 && TREE[i].weight < TREE[*s1].weight)
			*s1 = i;
	}
	TREE[*s1].flag = 1;
	for (i = 1; i <= n; i++)
	{
		if (TREE[i].flag == 0)
		{
			*s2 = i;
			break;
		}
	}
	for (i = (*s2) + 1; i <= n; i++)
	{
		if (TREE[i].flag == 0 && TREE[i].weight < TREE[*s2].weight)
			*s2 = i;
	}
	TREE[*s2].flag = 1;
}

void create_tree(HT *TREE, int n)		//Create Huffman Tree
{
	int m, i, s1, s2;
	m = 2 * n - 1;
	for (i = n + 1; i <= m; i++)
	{
		select_min(TREE, i-1, &s1, &s2);
		TREE[s1].parent = i;
		TREE[s2].parent = i;
		TREE[i].lchild = s1;
		TREE[i].rchild = s2;
		TREE[i].weight = TREE[s1].weight + TREE[s2].weight;
		TREE[i].flag = 0;				//initial
	}
	TREE[m].parent = 0;		//The root node
}

int calculate_length(HT *TREE, int *sum, int n)		//Calculate the minimum length of the path
{
	int i, m, length = 0;
	for (i = 1; i <= n; i++)
	{
		m = TREE[i].parent;
		while (m != 0)
		{
			sum[i]++;			//Sum storages the length of each node
			m = TREE[m].parent;
		}
	}
	for (i = 1; i <= n; i++)
		length += sum[i] * TREE[i].weight;
	return length;
}

int main()
{
	int i, N;
	int *sum;
	HT TREE[MAX];
	scanf("%d", &N);
	for (i = 1; i <= N; i++)			//Position 0 is not used
	{
		scanf("%d", &TREE[i].weight);
	}
	sum = (int *)malloc(N*sizeof(int));
	for (i = 1; i <= N; i++)
		sum[i] = 0;
	initial(TREE, N);
	create_tree(TREE, N);
	printf("%d\n", calculate_length(TREE, sum, N));
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值