1588: 合并果子
Time Limit: 1 Sec Memory Limit: 128 Mb Submitted: 1729 Solved: 783Description
现在有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
似乎有点像是构造哈夫曼树的过程。每次选最小的两个数,删除这两个数并将两个数的和加入进去。
#include<iostream>
#include<queue>
using namespace std;
int main()
{
priority_queue<int, vector<int>, greater<int> > pq;//优先队列,会自动按从小到大排序
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
while (n--)
{
int a;
cin >> a;
pq.push(a);
}
int a, b, c, num = 0;
while (pq.size() >= 2)
{
a = pq.top();//取队头,然后删除队头元素。因为自动排序,所以队头元素一定是最小的
pq.pop();
b = pq.top();
pq.pop();
num += a + b;
pq.push(a + b);
}
pq.pop();
cout << num << endl;
}
return 0;
}