k叉哈夫曼树 - NOI2015荷马史诗

Analysis

k叉哈夫曼树解析
这道题稍微还需要注意一点的就是最后还要求最长长度最短
这个其实就是在面对两个权值相同的情况下,优先合并深度较小的点


Code
#include<bits/stdc++.h>
#define re register
#define in read()
using namespace std;
inline char nc(){
	static char buf[100000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
typedef long long ll;
inline ll read(){
	char ch;int f=1;ll res=0;
	while((ch=nc())<'0'||ch>'9') if(ch=='-') f=-1;
	while(ch>='0'&&ch<='9'){
		res=(res<<1)+(res<<3)+(ch^48);
		ch=nc();
	}
	return f==1?res:-res;
}
struct node{
	ll val,dep;
	bool operator <(const node &a)const{
		if(val==a.val) return dep>a.dep;
		return val>a.val;
	}
};
priority_queue<node> q;
const int N=1e5+10;
int n,K;
ll ans=0,ans2=0;
void work(){
	while(n>1){
		ll new_val=0,new_dep=0;
		for(re int i=1;i<=K;++i){
			node tmp=q.top();q.pop();
			new_val+=tmp.val;
			new_dep=max(new_dep,tmp.dep+1);
		}
		q.push((node){new_val,new_dep});
		ans+=new_val;ans2=max(ans2,new_dep);
		n-=(K-1);
	}
	return ;
}
int main(){
//	freopen("data.in","r",stdin);
	ll x;
	n=in;K=in;
	for(re int i=1;i<=n;++i) x=in,q.push((node){x,0});
	int _left=(n-1)%(K-1);
	if(_left){_left=K-1-_left;for(re int i=1;i<=_left;++i)	q.push((node){0,0});}
	work();
	printf("%lld\n%lld",ans,ans2);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值