Huffman编码树

/*
1:Huffman编码树
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 65536kB
描述
构造一个具有n个外部节点的扩充二叉树,每个外部节点Ki有一个Wi对应,作为该外部节点的权。
使得这个扩充二叉树的叶节点带权外部路径长度总和最小:
         Min( W1 * L1 + W2 * L2 + W3 * L3 + … + Wn * Ln)
Wi:每个节点的权值。
Li:根节点到第i个外部叶子节点的距离。
编程计算最小外部路径长度总和。
输入
第一行输入一个整数n,外部节点的个数。第二行输入n个整数,代表各个外部节点的权值。
2<=N<=100
输出
输出最小外部路径长度总和。
样例输入
4
1 1 3 5
样例输出
17
*/

#include<iostream>
#include<algorithm>
#include<queue>
#include<functional>
using namespace std;
struct Node
{
	int value,depth;
	Node *left, *right;
	Node(int v)
	{
		value = v;
		depth = 0;
		left = NULL;
		right = NULL;
	}
};
struct Greater
{
	bool operator () (const Node *x, const Node *y)
	{
		return x->value > y->value;
	}
};
int cal(Node *root)
{
	if (root->left == NULL  && root->right == NULL)
		return root->value * root->depth;
	return cal(root->left) + cal(root->right);
}
void dep(Node *root)
{
	if (root == NULL)
		return;
	root->depth++;
	Node *l1 = root->left;
	Node *l2 = root->right;
	dep(root->left);
	dep(root->right);
}
int main()
{
	int t, m, i;
	cin >> t;
	priority_queue<Node*,vector<Node*>,Greater> heap;  //建立最小堆
	for (i = 0; i < t; ++i)
	{
		cin >> m;
		Node *l = new Node(m);
		heap.push(l);
	}
	Node *l1,*l2,*l3;
	while (heap.size() > 1)
	{
		l1 = heap.top();
		heap.pop();
		l2 = heap.top();
		heap.pop();
		l3 = new Node(l1->value + l2->value);
		l3->left = l1;
		l3->right = l2;
		l3->depth = -1;
		dep(l3);
		heap.push(l3);
	}
	l3 = heap.top();
	cout << cal(l3);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值