CF34B Sale| 贪心

题目描述

Once Bob got to a sale of old TV sets. There were nn TV sets at that sale. TV set with index ii costs a_{i}ai​ bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most mm TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.

输入格式

The first line contains two space-separated integers nn and mm ( 1<=m<=n<=100 ) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains nn space-separated integers a_{i}ai​ ( -1000<=a_{i}<=1000 ) — prices of the TV sets.

输出格式

Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most mm TV sets.

题意翻译

Bob要去参加一次旧电视卖场,一共有n台电视出售,编号为i的电视的价格为a_iai​。有些电视的价格是个负数,Bob最多会买m台电视,问Bob最多能赚到多少钱。

输入:

第一行两个整数n,m(1≤m≤n≤100),为待出售的电视机的数目和Bob打算买的电视机的数目。第二行有n个整数,整数之间用空格分开,第i个整数ai​(−1000≤ai​≤1000)为第i台电视机的价格.

输出:

输出只有一个数字,即Bob最多能赚到的钱。 Translated by @sounkix

输入输出样例

输入 #1

5 3
-6 0 35 -2 4

输出 #1

8

输入 #2

4 2
7 0 0 -7

输出 #2

7

解题思路:

把价格按照从小到大的顺序排好,一定要注意题目中说的最多,也就是只要把商家倒贴的钱累加起来就是赚的最多钱。因此只需要判断一下小于等于0的数与m谁大谁小。如果大的话,只需要从小取到m即可,反之只需要把所有小于等于0的累加即可(别忘了最后的abs(sum)).

代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=110;
int a[maxn];
int main(){
    int n,m;
    cin>>n>>m;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    sort(a,a+n);
    int ans=0,s=0;
    for(int i=0;i<n;i++){
        if(a[i]<=0){
            ans++;
        }
    }
    if(ans<m){
        for(int i=0;i<ans;i++){
            s+=a[i];
        }
    }else{
        for(int i=0;i<m;i++){
            s+=a[i];
        }
    }
    cout<<abs(s)<<endl;
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值