您的位置:首页 > 其它

Huffman编码树

2015-12-08 17:23 176 查看
/*
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: