UVa 10954 Add All(贪心)

5 篇文章 0 订阅



Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a C/C++ program just to add a set of numbers. Such a problem will simply question your erudition. So, lets add some flavor of ingenuity to it. 

 

Addition operation requires cost now, and the cost is the summation of those two to be added. So, to add 1 and 10, you need a cost of 11. If you want to add 12 and 3. There are several ways 

 

1 + 2 = 3, cost = 3

3 + 3 = 6, cost = 6

Total = 9

1 + 3 = 4, cost = 4

2 + 4 = 6, cost = 6

Total = 10

2 + 3 = 5, cost = 5

1 + 5 = 6, cost = 6

Total = 11

 

I hope you have understood already your mission, to add a set of integers so that the cost is minimal. 

 

一.思路

稍微思考一下就会发现:首先我们不论怎样选择合并,我们合并的总次数是一定的,也就是说我们做的合并序列长度已定,那么我们先使用贪心来思考,只要我们每一次合并的cost最小那么我们和起来的序列总cost是否就是最小的?很显然当然不一定,因为我们当前的选择两个值的和回作为元素在此出现在序列里面,也就是说合并的贪心选择会影响后续的结果,但是我们进一步思考发现,贪心产生的元素也应该是最小的,这样这个贪心的策略应该就是可以的了。
//
//  main.cpp
//  UVa 10954
//
//  Created by 张嘉韬 on 16/7/3.
//  Copyright © 2016年 张嘉韬. All rights reserved.
//

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n,sum;
int main(int argc, const char * argv[]) {
    while(cin>>n&&n!=0)
    {
        sum=0;
        priority_queue <int> q;
        for(int i=1;i<=n;i++)
        {
            int temp;
            cin>>temp;
            q.push(-temp);
        }
        while(!(q.size()==1))
        {
            int temp;
            temp=-q.top();
            //cout<<temp<<" ";
            q.pop();
            temp+=-q.top();
            //cout<<-q.top()<<" "<<endl;
            q.pop();
            sum+=temp;
            q.push(-temp);
        }
        cout<<sum<<endl;
        cout<<endl;
    }
    return 0;
}

Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a C/C++ program just to add a set of numbers. Such a problem will simply question your erudition. So, lets add some flavor of ingenuity to it. 

 

Addition operation requires cost now, and the cost is the summation of those two to be added. So, to add 1 and 10, you need a cost of 11. If you want to add 1, 2 and 3. There are several ways 

 

1 + 2 = 3, cost = 3

3 + 3 = 6, cost = 6

Total = 9

1 + 3 = 4, cost = 4

2 + 4 = 6, cost = 6

Total = 10

2 + 3 = 5, cost = 5

1 + 5 = 6, cost = 6

Total = 11

 

I hope you have understood already your mission, to add a set of integers so that the cost is minimal. 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值