【算法筆記第9.8節-哈夫曼編碼】問題 C: 哈夫曼樹(最小帶權路徑長度)

問題 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
****************************************************************/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章