北郵機試 哈夫曼樹

#include <stdio.h>
#include <queue>
using namespace std;
priority_queue<int, vector<int>, greater<int> > Q;
int main() {
    int n;
    while (scanf("%d", &n) != EOF)
    {
        while (Q.empty() == false)
            Q.pop();
        for (int i = 1; i <= n; i++)
        {
            int x;
            scanf("%d", &x);
            Q.push(x);
        }
        int ans = 0;
        while (Q.size() > 1)
        {
            int a = Q.top();
            Q.pop();
            int b = Q.top();
            Q.pop();
            ans += a + b;
            Q.push(a + b);
        }
        printf("%d\n", ans);
    }
    return 0;
}
 
/**************************************************************
    Problem: 1106
    User: mykelia
    Language: C++
    Result: Accepted
    Time:0 ms
    Memory:932 kb
****************************************************************/


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