【二叉哈弗曼树】 合并果子

传送门

题意

\(n\)堆果子,每一堆果子有重量\(w_{i}\),合并两堆果子消耗的体力等于重量之和,所有的果子经过\(n-1\)次合并后就剩下一堆,最后消耗的总体力等于每次合并的消耗,求出消耗体力的最小值

数据范围

\(\begin{array}{l}1 \leq n \leq 10000 \\ 1 \leq a_{i} \leq 20000\end{array}\)

题解

\(huffman\)树,用堆来实现,每次取最小的两个值加起来再存入堆之中,过程累计总和

Code

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)

int n;
priority_queue<int,vector<int>,greater<int>>q;
int main()
{
    cin>>n;
    rep(i,1,n+1)
    {
        int x; 
        cin>>x;
        q.push(x);
    }
    int ans=0;
    rep(i,1,n)
    {
        int x=q.top();q.pop();
        int y=q.top();q.pop();
        ans+=x+y;
        q.push(x+y);
    }
    cout<<ans<<endl;
} 
posted @ 2020-05-23 00:43  Hyx'  阅读(126)  评论(0)    收藏  举报