现在有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
思路:每次进行排序,排序后把最小的两个合成一堆,利用sum来储存总代价,s储存每次合并的代价。
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
while (n--)
{
int t;
cin >> t;
int *a = new int[t];
for (int i = 0; i < t; i++)
{
cin >> a[i];
}
sort(a, a + t);
int s = a[0];
int sum = 0;
for (int i = 0; i < t; i++)
{
a[i - 1] = s;
sort(a + i - 1, a + t);
s = a[i - 1] + a[i];
sum += s;
}
cout << sum << endl;
}
}