当前位置: 首页 > news >正文

A. Greedy Monocarp

time limit per test:2 seconds

memory limit per test:512 megabytes

There are n chests(箱子); the i-th chest initially contains ai coins. For each chest, you can choose any non-negative(非负) (0 or greater) number of coins to add to that chest, with one constraint(限制): the total number of coins in all chests must become at least k.

After you've finished adding coins to the chests, greedy Monocarp comes, who wants the coins. He will take the chests one by one, and since he is greedy, he will always choose the chest with the maximum number of coins. Monocarp will stop as soon as the total number of coins in chests he takes is at least k.

You want Monocarp to take as few coins as possible, so you have to add coins to the chests in such a way that, when Monocarp stops taking chests, he will have exactly k coins. Calculate the minimum number of coins you have to add.


题目解析

我们的目标是(1)让他恰好拿到k个硬币即可,并且(2)要求给箱子中加的硬币的数量是最少的。

首先从大到小排序。

(1)不用加硬币就能够让他恰好拿到k个硬币,输出0,k == sum

需要加硬币:查看需要加多少个能使得恰好拿到k个硬币

        (2)没遍历完整个数组。遍历到某个ai超过了k。===> k - (sum - ai)

        (3)遍历完整个数组。整合数组的和不足k。=====> k -  sum。

一共以上三种情况。

代码

#include<bits/stdc++.h>
using namespace std;void go()
{int n, k;cin >> n >> k;int a[n + 1];for(int i = 0; i < n; i++)cin >> a[i];sort(a, a + n, greater<int>());//从大开始遍历int sum = 0;int f = -1;for(int i = 0; i < n; i++){sum += a[i];if(sum >= k){f = i;break;}}if(sum == k){//刚好合适cout << 0 << endl;}else if (sum > k){//超过了cout << k - (sum - a[f]) << endl;}else if(sum < k){//不足cout << k - sum << endl;}
}
int main()
{int t;cin >> t;while(t--){go();}return 0;
}

相关文章:

  • 详解什么是One-Hot Encoding (独热编码)
  • 大数据学习(135)-Linux系统性指令
  • MinHook 如何对.NET底层的 Win32函数 进行拦截(上)
  • DAY 49 CBAM注意力
  • MCP笔记:UVX和NPX
  • Angular微前端架构:Module Federation + ngx-build-plus (Webpack)
  • C语言数据结构笔记4:子函数中使用的sizeof 指针无法获取数组的实际大小
  • 国内外UI自动化测试工具全景分析:国产创新与国际领先工具对比
  • 俩人相向而行,何时相遇问题思考。
  • 软件定义车辆加速推进汽车电子技术的未来发展
  • 使用黑马X2C
  • leetcode刷题经验
  • python打卡day49
  • 从零手写Java版本的LSM Tree (二):KeyValue 数据结构
  • 制作一款打飞机游戏68:地面敌人
  • 使用python进行图像处理—像素级操作与图像算术(4)
  • CMake 从 GitHub 下载第三方库并使用
  • 使用python进行图像处理—图像变换(6)
  • 从零手写Java版本的LSM Tree (一):LSM Tree 概述
  • 安宝特方案丨船舶智造AR+AI+作业标准化管理系统解决方案(维保)
  • wordpress摘要两端对齐/上海全国关键词排名优化
  • 支付宝网站支付接口/seo搜索引擎优化心得体会
  • 怎么样才能自己做网站打广告/网站推广优化方案
  • 可以做宣传图的网站/新东方在线网上课程
  • 中国建设银行网站首/宁德市安全教育平台
  • 网站建设免费免代码/搭建网站费用是多少