BZOJ 4198: [Noi2015]荷马史诗 哈夫曼树 k叉哈夫曼树

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

https://blog.csdn.net/chn_jz/article/details/76695514

k叉需要通过补0来填满树。顺便复习一下重载运算符,别忘了优先队列的比较是反的。。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<iostream>
 6 #include<queue>
 7 using namespace std;
 8 #define LL long long
 9 LL n,k;
10 struct nod{
11     LL x,d;
12     bool operator<(const nod &z)const{
13         if(z.x==x)return d>z.d;
14         return x>z.x;
15     }
16 };
17 priority_queue< nod >q;
18 int main(){
19     nod v;v.d=0;
20     scanf("%lld%lld",&n,&k);
21     for(int i=1;i<=n;i++){scanf("%lld",&v.x);q.push(v);}
22     LL ans=0,ans1=0,zz,zz1;bool f=0;
23     if(k>2){
24         while(n%(k-1)!=1){
25             ++n;v.x=0;q.push(v);
26         }
27     }
28     while(!q.empty()){
29         zz=0;zz1=0;
30         for(int i=1;i<=k;i++){
31             if(q.empty()){f=1;break;}
32             v=q.top();q.pop();
33             zz+=v.x;zz1=max(zz1,v.d);
34         }
35         if(f)break;
36         ans+=zz; v.x=zz; v.d=zz1+1;
37         ans1=max(zz1+1,ans1);
38         q.push(v);
39     }
40     printf("%lld\n%lld\n",ans,ans1);
41     return 0;
42 }
View Code

 

posted @ 2018-06-02 11:44  鲸头鹳  阅读(132)  评论(0编辑  收藏  举报