UVA 10954 Add All【优先队列简单应用】

题目大意:对于一组数不同求和方法中,每步累加和之和最小,详细见样例。

解题策略:运用优先队列(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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值