AT_abc437_c [ABC437C] Reindeer and Sleigh 2 题解

· · 题解

解题思路

考虑贪心,首先容易想到按照 W_i 或者 P_i 排序,然后一个一个试,直到满足力量之和大于等于重量。

实践出真知,发现只过了两个点,于是考虑修改做法。由于以上做法假得没边,所以就不予解释,大家随便手搓几组数据就好。希望大家不要像我一样白吃罚时。

如果所有鹿都去拉车,那么显然一定合法。那么考虑让一只鹿去坐车,那么拉力减少 P_i,重量增加 W_i。

设 \sum_{i = 1} ^ n P_i 为 T。那么拉力与重量的差值由 T 变为 T - P_i - W_i。差值减少了 P_i + W_i,显然 P_i + W_i 越大一定越优,所以将其从大到小排序,一个一个试就好了。

CODE:

#include <bits/stdc++.h>
using namespace std;
#define int long long
struct node {
    int w, p;
} a[300010];
signed main() {
    ios::sync_with_stdio(false);
    ios_base::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    int T;
    cin >> T;
    while (T--) {
        int n;
        cin >> n;
        int ans1 = 0, ans2 = 0;
        for (int i = 1; i <= n; i++) {
            cin >> a[i].w >> a[i].p;
            ans2 += a[i].w;
        }
        sort(a + 1, a + 1 + n, [](node a, node b) {
            return a.p + a.w > b.p + b.w;
        });
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            ans1 += a[i].p;
            ans2 -= a[i].w;
            if (ans1 >= ans2) {
                ans = n - i;
                break;
            }
        }
        cout << ans << "\n";
    }
    return 0;
}