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

货真价实的水题,学点c++或者能写堆排序的都能过。

#include <cstdio>
#include <queue> 

using namespace std;

struct cmp{
	bool operator()(int a,int b){
		return a > b;
	}
};

priority_queue<int,vector<int>,cmp>Q;

int main(){
	
	int T,N;
	scanf("%d",&T);
	long long sum;
	int mid; 
	while(T--){
		scanf("%d",&N);
		sum = 0;
		for(int _=0 ; _<N ; _++){
			scanf("%d",&mid);
			Q.push(mid);
		}
		while(!Q.empty()){
			mid = Q.top();
			Q.pop();
			if(Q.empty())break;
			mid += Q.top();
			Q.pop();
			Q.push(mid);
			sum += mid;
		}
		printf("%d\n",sum);
	}
	
	return 0;
}




猜你喜欢

转载自blog.csdn.net/vocaloid01/article/details/80499059