問題 C: 哈夫曼樹
時間限制: 1 Sec 內存限制: 32 MB
提交: 149 解決: 88
[提交][狀態][討論版][命題人:外部導入]
題目描述
哈夫曼樹,第一行輸入一個數n,表示葉結點的個數。需要用這些葉結點生成哈夫曼樹,根據哈夫曼樹的概念,這些結點有權值,即weight,題目需要輸出所有結點的值與權值的乘積之和。
輸入
輸入有多組數據。
每組第一行輸入一個數n,接着輸入n個葉節點(葉節點權值不超過100,2<=n<=1000)。
輸出
輸出權值。
樣例輸入
2 2 8 3 5 11 30
樣例輸出
10 62
優先隊列(小頂堆)
#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
priority_queue<int, vector<int>, greater<int> > q;
int t;
for(int i=0; i<n; i++)
{
scanf("%d",&t);
q.push(t);
}
int ans = 0;
while(q.size() > 1)
{
int a, b;
a = q.top(); q.pop();
b = q.top(); q.pop();
ans += (a+b);
q.push(a+b);
}
printf("%d\n", ans);
}
}
/**************************************************************
Problem: 1921
User: 151210132
Language: C++
Result: 正確
Time:0 ms
Memory:1172 kb
****************************************************************/