构造哈夫曼树的哈夫曼算法

2022-06-28 18:37:00 浏览数 (1)

本文最后更新于 1170 天前,其中的信息可能已经有所发展或是发生改变。

代码语言:javascript复制
#include "stdafx.h"
#include "stdio.h"
#define maxval 100.0 
#pragma warning(disable:4996)
typedef struct{
	float weight;
	int parent, lchild, rchild;
}hufmtree;
void Huffman(hufmtree tree[])
{
	int i, j, p1, p2; int n, m;
	float sum = 0; 
	float small1, small2, f;
	puts("请输入叶子结点的数目");
	scanf("%d", &n);
	m = 2 * n - 1;
	for (i = 0; i < m; i  )
	{
		tree[i].parent = 0;
		tree[i].lchild = 0;
		tree[i].rchild = 0;
		tree[i].weight = 0.0;
	}
	printf("请输入%d个权值n", n);
	
	for (i = 0; i < n; i  )
	{

		scanf("%f", &f);
		tree[i].weight = f;
	}
	for (i = n; i < m; i  ){
		p1 = p2 = 0;
		small1 = small2 = maxval;
		for (j = 0; j <= i - 1; j  ){ 
			if (tree[j].parent == 0)
			if (tree[j].weight < small1){
				small2 = small1;
				small1 = tree[j].weight;
				p2 = p1;
				p1 = j;
			}
			else
			if (tree[j].weight < small2){
				small2 = tree[j].weight;
				p2 = j;
			}
		}
		tree[p1].parent = tree[p2].weight = i;
		tree[i].weight = tree[p1].weight   tree[p2].weight;
		sum  = tree[j].weight;
		tree[i].lchild = p1;
		tree[i].rchild = p2;
	}
	printf("哈夫曼树为; n parent lchild rchild weightn");
	for (i = 0; i < 2 * n - 1; i  )
	{
		printf(" %d      %d      %d      %.2fn", tree[i].parent,
			tree[i].lchild, tree[i].rchild, tree[i].weight);
	}
	printf("带权路径长度为:%.2fn", sum);
}
int main()
{
	hufmtree tree[100];
	Huffman(tree);
}

Post Views: 184

0 人点赞