题目大意:对于一组数不同求和方法中,每步累加和之和最小,详细见样例。
解题策略:运用优先队列(priority_queue),每次取队列中最小的前两值取和,累加。
第一次用优先队列,mark下
/*
UVA 10954 Add All
AC by J.Dark
ON 2013/4/7
Time 0.048s
*/
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 5005;
struct cmp{
bool operator()(int x, int y){
return x > y;
}
};
int main(){
priority_queue <int, vector<int>, cmp> q;
int testCase, temp, minCost;
while(cin >> testCase && testCase)
{
for(int i=0; i<testCase; i++){
cin >> temp;
q.push(temp);
}
int cur1, cur2;
minCost = 0;
while(!q.empty())
{
cur1 = q.top();
q.pop();
if(q.empty()) break; //之前代码贴错,判断是否计算到最终结果
cur2 = q.top();
q.pop();
minCost += (cur1+cur2);
q.push(cur1+cur2);
}
cout << minCost << endl;
}
return 0;
}