CSU 1588 合并果子

现在有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

这题可以用最小生成树去做的,因为数据有点水,所以你也可以每次找了之后排序下,然后重新找,然后再排序下就好了;排序方式最好用插入排序,当我们第一次排序之后再做插入,其实这个数组就其他值都已经是排好序的了,所以用插入排序之后时间效率其实可以达到(On)的;

这里我用的是优先队列来处理,处理起来就简单很多了,只要加入好了优先级就可以了:


#include
#include
#include
#include
using namespace std;
struct cmp
{
	bool operator()(const int a,int b)
	const{
		return a>b;
	}
};
int main()
{
	int T,n,a;
	cin>>T;
	while(T--)
	{
		priority_queue,cmp> pq;
		cin>>n;
		for(int i=0;i>a;
			pq.push(a);
		}
		int x,y,res;
		int sum=0;
		while(!pq.empty()&&pq.size()!=1)
		{
			x=pq.top();
			pq.pop();
			y=pq.top();
			res=x+y;
			pq.pop();
			pq.push(res);
			sum+=res;
		}
//		cout<


你可能感兴趣的:(队列,最小生成树)