很简单的一道优先队列问题,思路如下:
每次合并最小的两堆,并把新堆放入队列中,直到只剩下一堆为止
注意:
1 优先队列让最小的在队首要用greater<>,最大的要用less
2每次从优先队列取出两个值取两个值,因此当只剩下一个值的时候无法再取两个值了
代码如下:
#include<iostream>
#include<string>
#include<queue>
#include<algorithm>
#include<set>
using namespace std;
struct cmp{
bool operator ()(long long &a,long long &b){
return a>b;
}
};
int main(){
int test;
cin>>test;
while(test--){
int n;
cin>>n;
priority_queue<long long ,vector<long long>,cmp>q;
for(int i=1;i<=n;i++){
int temp;
cin>>temp;
q.push(temp);
}
long long ans=0;
while(!q.empty()){
int t1,t2;
t1=q.top();
q.pop();
if(q.empty())break;
t2=q.top();
q.pop();
ans+=t1+t2;
q.push(t1+t2);
// cout<<ans<<" ";
}
cout<<ans<<endl;
}
}