传送门
多叉哈夫曼树,唯一需要注意的是如果
就要补上
个空节点
#include<cstdio>
#include<iostream>
#include<queue>
#define LL long long
using namespace std;
const int N=1000000;
LL n,k,w[N],v[N],ans,mxdep;
struct data{
LL w,sum,num;
};
struct cmp{
bool operator() (data q,data w){
if (q.w>w.w) return 1;
if (q.w<w.w) return 0;
else return q.sum>w.sum;
}
};
priority_queue<data,vector<data>,cmp> h;
void read(LL &x){
char ch=getchar();x=0;
for(;ch<'0'||ch>'9';ch=getchar());
for(;ch>='0'&&ch<='9';ch=getchar()) x=(x<<3)+(x<<1)+ch-'0';
}
int main(){
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
read(n);read(k);
for(int i=1;i<=n;i++){
read(v[i]);
data q;
q.w=v[i];q.sum=1;q.num=i;
h.push(q);
}
if ((n-1)%(k-1)) for(int i=1;i<=k-1-(n-1)%(k-1);i++){ data q;q.w=0;q.sum=1;q.num=n+i;h.push(q); }
w[0]=((n-2)/(k-1)+1)*(k-1)+1;
for(int o=1;o<=(n-2)/(k-1)+1;o++){
data s;s.w=0;s.sum=0;s.num=++w[0];
for(int i=1;i<=k;i++){
data q=h.top();h.pop();
w[q.num]=s.num;
s.w+=q.w;s.sum+=q.sum;
}
h.push(s);
}
for(int i=1;i<=n;i++){
LL dep=0;
for(int j=i;j!=w[0];dep++,j=w[j]);
mxdep=max(mxdep,dep);
ans+=v[i]*dep;
}
cout<<ans<<endl<<mxdep<<endl;
// for(int i=1;i<=w[0];i++) cout<<w[i]<<' ';
return 0;
}