假设有n个权值,则构造出的哈夫曼树有n个叶子结点。 n个权值分别设为 w1、w2、…、wn,则哈夫曼树的构造规则为[1]:
(1) 将w1、w2、…,wn看成是有n 棵树的森林(每棵树仅有一个结点);
(2) 在森林中选出两个根结点的权值最小的树合并,作为一棵新树的左、右子树,且新树的根结点权值为其左、右子树根结点权值之和;
(3)从森林中删除选取的两棵树,并将新树加入森林;
(4)重复(2)、(3)步,直到森林中只剩一棵树为止,该树即为所求得的哈夫曼树。
51nod 1117
#include <bits/stdc++.h> using namespace std; priority_queue<int, vector<int>, greater<int>> Q; int main() { int n, input, ans = 0; cin >> n; for (int i = 0; i < n; i++) { cin >> input; Q.push(input); } while (!Q.empty()) { int a, b; a = Q.top(); Q.pop(); if (Q.empty()) break; b = Q.top(); Q.pop(); ans += a+b; Q.push(a+b); } cout << ans << endl; return 0; }
Reference:
[1] 百度百科:哈夫曼树.