本文最后更新于 1170 天前,其中的信息可能已经有所发展或是发生改变。
#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 weight\n");
for (i = 0; i < 2 * n - 1; i++)
{
printf(" %d %d %d %.2f\n", tree[i].parent,
tree[i].lchild, tree[i].rchild, tree[i].weight);
}
printf("带权路径长度为:%.2f\n", sum);
}
int main()
{
hufmtree tree[100];
Huffman(tree);
}
Post Views: 184
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有