codeforce884 D. Boxes And Balls
给定n个球,每个球有一定价值,求将其按照价值的分类的最小价值
逆过程:将n个一定价值的球合并到一起的最小费用,构造哈夫曼树:带权路径长度最短的树,权值较大的结点离根较近
#include<bits/stdc++.h>
using namespace std;
const int MAX=2e5+5;
int n;
priority_queue<long long,vector<long long>,greater<long long> >q;
int main()
{
long long x;
while(~scanf("%d",&n))
{
while(!q.empty()) q.pop();
for(int i=0;i<n;++i){scanf("%lld",&x);q.push(x);}
if((n&1)==0) q.push(0);
long long ans=0;
while(q.size()>1)
{
x=q.top();q.pop();
x+=q.top();q.pop();
x+=q.top();q.pop();
q.push(x);
ans+=x;
}
printf("%lld\n",ans);
}
return 0;
}