哈夫曼樹,第一行輸入一個數n,表示葉結點的個數。需要用這些葉結點生成哈夫曼樹,根據哈夫曼樹的概念,這些結點有權值,即weight,題目需要輸出所有結點的值與權值的乘積之和。
輸入描述:
輸入有多組數據。
每組第一行輸入一個數n,接着輸入n個葉節點(葉節點權值不超過100,2<=n<=1000)。
輸出描述:
輸出權值。
示例1
輸入
5
1 2 2 5 9
輸出
37
解題思路:
典型的求解哈夫曼樹,使用優先隊列可大大簡化代碼量。
AC代碼:
#include <iostream>
#include <queue>
#include <functional>
using namespace std;
int main() {
int n;
priority_queue<int, vector<int>, greater<int> > Q;
while (cin >> n) {
while (Q.empty() == false) Q.pop();
for (int i = 0; i < n; i++) {
int x;
cin >> x;
Q.push(x);
}
int ans = 0;
while (Q.size() > 1) {
int a = Q.top();
Q.pop();
int b = Q.top();
Q.pop();
ans = ans + a + b;
Q.push(a + b);
}
cout << ans << endl;
}
return 0;
}