noip 2004 合并果子

来源:互联网 发布:佛教的软件 编辑:程序博客网 时间:2024/06/06 17:11

合并果子

Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%lld & %llu

Description

现在有n堆果子,第i堆有ai个果子。现在要把这些果子合并成一堆,每次合并的代价是两堆果子的总果子数。求合并所有果子的最小代价。

Input

第一行包含一个整数T(T<=50),表示数据组数。
每组数据第一行包含一个整数n(2<=n<=1000),表示果子的堆数。
第二行包含n个正整数ai(ai<=100),表示每堆果子的果子数。

Output

每组数据仅一行,表示最小合并代价。

Sample Input

241 2 3 453 5 2 1 4

Sample Output

1933

树和STL优先队列也能做,题目思想很明确,用贪心做出。
先用STL中的 priority_queue<int , vector<int> ,greater<int> > x  函数,即优先队列,把最小的两个数相加。
在 priority_queue<int , vector<int> ,greater<int> > x,x表示一个“越小的整数优先级越大的优先队列” ,
#include<cstdio>#include<cstring>#include<iostream>#include<utility>#include<string>#include<vector>#include<algorithm>#include<queue>#include<cstdlib>#include<cmath>#include<stack>using namespace std;priority_queue<int , vector<int> ,greater<int> > x ;int main(){#ifndef ONLINE_JUDGEfreopen("1.txt","r",stdin);#endifint t;cin >> t ;while (t--){int n , i , a[1005] , ans = 0 ;cin >> n ;for(i = 0 ; i < n ; ++i){cin >> a[i] ;x.push(a[i]);}while(x.size() > 1){n = x.top() ;x.pop();n += x.top() ;x.pop();ans += n ;if(x.empty())break;x.push(n);}printf("%d\n",ans);}return 0;}

而单单的 priority_queue<int> x则可以表示为一个 “越小的整数优先级越低的优先队列”。
0 0