#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;
}
DSOJ Huffman coding tree(Huffman编码树)
最新推荐文章于 2024-01-01 15:59:51 发布