bzoj 4198 [ Noi 2015 ] 荷马史诗 —— 哈夫曼编码(k叉哈夫曼树)
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4198
第一次写哈夫曼树!看了很多博客。
哈夫曼树 & 哈夫曼编码:https://www.cnblogs.com/xidongyu/p/6031518.html
这道题:http://www.cnblogs.com/LadyLex/p/7503173.html
满 k 叉树节点数的判断:https://blog.csdn.net/cqbzwja/article/details/46974241
https://blog.csdn.net/morestep/article/details/47665135
真美啊!
代码如下:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; typedef long long ll; int n,k; struct N{ ll w,dep; N(ll w=0,int d=0):w(w),dep(d) {} bool operator < (const N &y) const { return w==y.w?dep>y.dep:w>y.w; } }ans; priority_queue<N>q; int main() { scanf("%d%d",&n,&k); ll x; for(int i=1;i<=n;i++) { scanf("%lld",&x); q.push(N(x,1)); } while(k>2&&n%(k-1)!=1)q.push(N(0,1)),n++; while(q.size()>1) { N nw; nw.w=nw.dep=0; for(int i=1;i<=k;i++) { N t=q.top(); q.pop(); nw.w+=t.w; nw.dep=max(nw.dep,t.dep+1); } ans.w+=nw.w; ans.dep=max(ans.dep,nw.dep); q.push(nw); } printf("%lld\n%d\n",ans.w,ans.dep-1); return 0; }