聰明的木匠 (哈夫曼樹)

假設有n個權值,則構造出的哈夫曼樹有n個葉子結點。 n個權值分別設爲 w一、w二、…、wn,則哈夫曼樹的構造規則爲[1]:
(1) 將w一、w二、…,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:c++

[1] 百度百科:哈夫曼樹.spa

相關文章
相關標籤/搜索