1588: 合併果子
Time Limit: 1 Sec Memory Limit: 128 Mb Submitted: 1351 Solved: 580Description
現在有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
Hint
Source
國防科學技術大學第十八屆銀河之光文化節ACM程序設計競賽初賽#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
priority_queue <int,vector<int>,greater<int> > q;
int main()
{
int t;
cin >> t;
while(t--)
{
int n;
int ans=0;
cin >> n;
int x;
while(!q.empty()) q.pop();
for(int i=0;i<n;i++)
{
cin >> x;
q.push(x);
}
while(!q.empty())
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
ans=ans+a+b;
q.push(a+b);
if(q.size()==1)
break;
}
cout << ans << endl;
}
return 0;
}