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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章