荷马史诗

k叉哈夫曼树,美极了,注意补齐(置0

#include<stdio.h>
#include<algorithm>
#include<queue>
using namespace std;

typedef long long i64;
typedef pair<i64,int>pii;
#define mp make_pair
#define fir first
#define sec second
priority_queue<pii,vector<pii>,greater<pii> >Q;

int main(){
    int n,k;i64 x;
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++){
        scanf("%lld",&x);
        Q.push(mp(x,0));
    }
    while((n-1)%(k-1)){
        Q.push(mp(0,0));
        n++;
    }
    i64 ans=0;
    while(Q.size()!=1){
        i64 sum=0;int dep=0;
        for(int i=0;i<k;i++){
            sum+=Q.top().fir;
            dep=max(dep,Q.top().sec);
            Q.pop();
        }
        ans+=sum;
        Q.push(mp(sum,dep+1));
    }
    printf("%lld\n%d\n",ans,Q.top().sec);
    return 0;
}
View Code

 

posted @ 2015-11-20 16:49  Ngshily  阅读(144)  评论(0编辑  收藏  举报