bzoj 4198 [Noi2015]荷马史诗——哈夫曼树

题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4198

学习一下哈夫曼树。https://www.cnblogs.com/Zinn/p/9400381.html

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define ll long long
using namespace std;
int n,k,ans;
ll sum;
struct Node{
    ll w;int dep;
    Node(ll w=0,int d=0):w(w),dep(d) {}
    bool operator< (const Node &b)const
    {return w==b.w?dep>b.dep:w>b.w;}//dep!!!
};
priority_queue<Node> q;
int main()
{
    ll x;
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)scanf("%lld",&x),q.push(Node(x,0));
    while(n%(k-1)!=1&&k!=2)n++,q.push(Node(0,0));
    while(q.size()>1)
    {
        n++;x=0;int d=0;
        for(int j=1;j<=k;j++)
        {
            Node k=q.top();q.pop();
            x+=k.w;sum+=k.w;d=max(d,k.dep);//max!!
        }
        q.push(Node(x,d+1));
        if(q.size()==1)ans=d+1;
    }
    printf("%lld\n%d\n",sum,ans);
    return 0;
}

 

posted on 2018-08-01 18:31  Narh  阅读(128)  评论(0编辑  收藏  举报

导航