1588: 合并果子
Time Limit: 1 Sec Memory Limit: 128 Mb
Description
现在有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程序设计竞赛初赛
题目链接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1588
题解:这道题看了别人的博客,了解到可以用优先队列、哈夫曼树、排序+贪心来解。但我个人还是用的优先队列(优先队列),毕竟这是最简单容易想到的。
AC代码
#include<iostream>
#include<queue>
using namespace std;
int main(){
int T;
scanf("%d",&T);
int n;
int tmp;
priority_queue<int,vector<int>,greater<int> >q;
while(T--){
scanf("%d",&n);
while(n--){
scanf("%d",&tmp);
q.push(tmp);
}
int x=0,y=0,sum=0;
while(!q.empty()){
x=q.top();
q.pop();
if(q.empty()){
break;
}
y=q.top();
q.pop();
sum+=(x+y);
q.push(x+y);
}
printf("%d\n",sum);
}
return 0;
}