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;
}