哈夫曼编码(4)
P2168 荷马史诗
题意:
k叉哈夫曼编码
要求哈夫曼树尽可能平衡
代码:
const ll N=2e5+10;
ll w[N];vector<ll> e[N];
ll cnt;
struct node{ll w,h,idx;};
struct cmp{
bool operator()(const node& nd1,const node& nd2){
return nd1.w==nd2.w ? nd1.h>nd2.h : nd1.w>nd2.w;
}
};
priority_queue<node,vector<node>,cmp> pq;
ll n,k,ans1,ans2;
void dfs(ll root,ll depth)
{
if(e[root].empty()){
//cerr<<root<<",,,"<<depth<<endl;
ans1+=w[root]*depth;
ans2=max(ans2,depth);
return;
}
for(ll i=0;i<k;++i){//非叶子节点一定有k个儿子
dfs(e[root][i],depth+1);
}
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0);
cin>>n>>k;
for(ll i=1;i<=n;++i){
cin>>w[i];
++cnt;
pq.push({w[i],0,cnt});
}
ll need=(k-1+(1-n)%(k-1))%(k-1);
for(ll i=1;i<=need;++i){
++cnt;
pq.push({0,0,cnt});
}
while(pq.size()>=k){
//cerr<<":"<<pq.size()<<endl;
++cnt;
w[cnt]=0;
ll h=0;
for(ll i=1;i<=k;++i){
node head=pq.top(); pq.pop();
w[cnt]+=head.w;
h=max(h,head.h);
e[cnt].push_back(head.idx);
}
pq.push({w[cnt],h+1,cnt});
}
dfs(cnt,0);
cout<<ans1<<"\n"<<ans2;
return 0;
}
参考:蓝桥杯官方书籍

浙公网安备 33010602011771号