1 3 1 2 9
15
思路:每次挑选当前堆中数目最少的两个,合并。。。
优先队列priority_queue
代码:
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#define LL long long
const int M = 100;
using namespace std;
struct cmp{
bool operator ()(int &a, int &b){
return a > b; //×îСֵÓÅÏÈ
}
};
struct node{
int x;
bool operator < (const node &a) const {
return x > a.x; // ×îСֵÓÅÏÈ
}
};
int main(){
int t, n, s[M];
cin >> t;
priority_queue <int, vector<int>, cmp> q;
while(t --){
while(!q.empty()) q.pop();
cin >> n;
int i, temp;
for(i = 0; i < n; ++ i){
cin >> temp;
q.push(temp);
}
LL sum = 0;
while(q.size() > 1){
int temp1 = q.top(); q.pop();
int temp2 = q.top(); q.pop();
// cout << temp1 << " " << temp2 << endl;
temp = temp1+temp2;
sum += temp; q.push(temp);
}
cout << sum << endl;
}
return 0;
}
原文地址:http://blog.csdn.net/shengweisong/article/details/44164615