[NOI2015]荷马史诗【哈夫曼编码】

[NOI2015]荷马史诗

推荐一篇题解
(感觉自己讲不清楚所以不如直接粘题解)
观察之后发现这就是哈夫曼编码,于是按照编码方式构造即可。

#include <bits/stdc++.h>
#define ll long long
#define int long long 
using namespace std;
struct node{
	ll w,h;
	node(){w=0,h=0;}
	node(ll w,ll h):w(w),h(h) {}
	bool operator <(const node &a)const {return a.w==w?h>a.h:w>a.w;}
};
ll ans,maxh;
int n,k,x,cnt;
priority_queue<node> q;
inline int read(){
	int cnt=0,f=1;char c=getchar();
	while(!isdigit(c)){if(c=='-')f=-f;c=getchar();}
	while(isdigit(c)){cnt=(cnt<<1)+(cnt<<3)+(c^48);c=getchar();}
	return cnt*f;
}
signed main(){
	n=read(),k=read();
	for(int i=1;i<=n;++i) {x=read(),q.push(node(x,1));}
	if((n-1)%(k-1)) cnt=k-1-((n-1)%(k-1));
	for(int i=1;i<=cnt;++i) q.push(node(0,1));
	cnt+=n;
	while(cnt>1){
		x=maxh=0;
		for(int i=1;i<=k;++i){
			x+=q.top().w;
			maxh=max(maxh,q.top().h);
			q.pop();
		}
		ans+=x;
		q.push(node(x,maxh+1));
		cnt-=k-1;
	}
	cout<<ans<<endl<<q.top().h-1<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值