以前在我们学校的OJ上做过一道类似的题目,一开始想模拟操作过程的但是实现不了,建立哈夫曼树又不会,后来跟同学学习了优先队列,所以就无节操的水过了啊、、、、
下面是代码
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int main()
{
long long n,i,t,tt,ans;
priority_queue<long long ,vector<long long >, greater<long long > >pq;
while(cin>>n)
{
for(i=0; i<n; i++)
{
cin>>t;
pq.push(t);
}
ans=0;
while(!pq.empty())
{
t=pq.top();
pq.pop();
if(pq.empty())
{
break;
}
else
{
tt=pq.top();
pq.pop();
tt=tt+t;
ans+=tt;
pq.push(tt);
}
}
cout<<ans<<endl;
}
return 0;
}