(树) 修理牧场 (25 分)【哈夫曼树/最优二叉树】

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
priority_queue<int, vector<int>, greater<int> > p;
int N, a;
int main()
{
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    scanf("%d", &N);
    for(int i = 0; i < N; i++)
    {
        scanf("%d", &a);
        p.push(a);
    }
    int x, y, ans = 0;
    while(p.size() > 1)
    {
        x = p.top();
        p.pop();
        y = p.top();
        p.pop();
        p.push(x + y);
        ans += (x + y);
    }
    while(p.size())
        p.pop();
    printf("%d\n", ans);
}
posted @ 2019-09-17 21:30  DIY-Z  阅读(238)  评论(0)    收藏  举报