Huffman编码树

来源:互联网 发布:c语言体会 编辑:程序博客网 时间:2024/06/06 01:51
/*1:Huffman编码树查看 提交 统计 提问总时间限制: 1000ms 内存限制: 65536kB描述构造一个具有n个外部节点的扩充二叉树,每个外部节点Ki有一个Wi对应,作为该外部节点的权。使得这个扩充二叉树的叶节点带权外部路径长度总和最小:         Min( W1 * L1 + W2 * L2 + W3 * L3 + … + Wn * Ln)Wi:每个节点的权值。Li:根节点到第i个外部叶子节点的距离。编程计算最小外部路径长度总和。输入第一行输入一个整数n,外部节点的个数。第二行输入n个整数,代表各个外部节点的权值。2<=N<=100输出输出最小外部路径长度总和。样例输入41 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 0
原创粉丝点击