Description
现在有n堆果子,第i堆有ai个果子。现在要把这些果子合并成一堆,每次合并的代价是两堆果子的总果子数。求合并所有果子的最小代价。
Input
第一行包含一个整数T(T<=50),表示数据组数。
每组数据第一行包含一个整数n(2<=n<=1000),表示果子的堆数。
第二行包含n个正整数ai(ai<=100),表示每堆果子的果子数。
Output
每组数据仅一行,表示最小合并代价。
Sample Input
2
4
1 2 3 4
5
3 5 2 1 4
Sample Output
19
33
解题思路
要使合并的费用最小,那么每次都需要合并最小的两堆…
AC代码
#include<iostream>
#include<queue>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> > node;
int t,n;
cin>>t;
while(t--)
{
int x,num=0;
cin>>n;
while(n--)
{
cin>>x;
node.push(x);
}
int x1,x2,x3;
while(!node.empty())
{
x1=node.top();
node.pop();
if(node.empty())
break;
x2=node.top();
node.pop();
x3=x1+x2;
num+=x3;
node.push(x3);
}
cout<<num<<endl;
}
}