https://www.hackerrank.com/contests/101hack41/challenges/washing-plates
给定n个物品,选这个物品,贡献 + p, 不选的话,贡献 - d
问最大贡献。
考虑贪心。优先选最好的k件。什么是最好呢。
把每个物品的p + d作为权值排序,最大的就是最好的。
因为要使得p + d最大,必然是p或者d是很大的,或者都大。这两个值对答案都有相同意义的贡献。就是你能选的话就能加很多,不选的话,就会减很多。

#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> using namespace std; #define inf (0x3f3f3f3f) typedef long long int LL; #include <iostream> #include <sstream> #include <vector> #include <set> #include <map> #include <queue> #include <string> const int maxn = 2e5 + 20; struct node { LL val; LL p, d; int id; }tosort[maxn]; bool cmp(node a, node b) { return a.val > b.val; } void work() { int n, k; cin >> n >> k; for (int i = 1; i <=n; ++i) { LL p, d; cin >> p >> d; tosort[i].val = p + d; tosort[i].id = i; tosort[i].p = p; tosort[i].d = d; } sort(tosort + 1, tosort + 1 + n, cmp); LL sum = 0; for (int i = 1; i <= k; ++i) { sum += tosort[i].p; } for (int i = k + 1; i <= n; ++i) { sum -= tosort[i].d; } sum = max(sum, 0LL); cout << sum << endl; } int main() { #ifdef local freopen("data.txt","r",stdin); #endif work(); return 0; }