贪心!

· · 题解

这里先说一个错解。有两个数组: v 储存编程队选出的学生,q 储存体育队选出的学生。如果 a_i > b_i,把 i 放进 v,否则放进 q。如果 v 中的元素个数大于 p,把 |a_i - b_i| 小的元素放进 p,直到合法。反之,如果 p 不符合条件,把 |a_i - b_i| 小的元素放进 v。为什么错了?可以构造一个 HACK:

3 2 0
20 10 6
16 1 1

此时,我们编程队选择的是 10 6,显然不是最大的。为什么?因为我们没有考虑一个元素的“重要性”,虽然它的 a_i 和 b_i 的相差不是很大,但是其他元素都太小了,可以移走其他的。

时间复杂度为 \mathcal{O}(n \log n)。

#include <bits/stdc++.h>
constexpr int N = 3e5 + 10;
using namespace std;
struct node {
    int val, i;
    bool operator< (const node &b) const {
        return val < b.val;
        // 大根堆
        // 这里有一个不寻常的写法:b.val > val
    }
};
int n, p, s;
int ans;
int a[N], b[N];
int v[N];
priority_queue<node> A, B, C;
int main() {
    cin >> n >> p >> s;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
        A.push({a[i], i});
    }
    while (p--) {
        ans += A.top().val;
        v[A.top().i] = 1;
        A.pop();
    }
    for (int i = 1; i <= n; ++i) {
        cin >> b[i];
        if (v[i]) C.push({b[i] - a[i], i});
        else B.push({b[i], i});
    }
    for (int i = 1; i <= s; ++i) {
        // A 和 B 装的都是没有选择的人
        // 这里,要保证都是没有队选择的点
        // 因为过程中有可能被其他队的选了
        while (!A.empty() && v[A.top().i]) A.pop();
        while (!B.empty() && v[B.top().i]) B.pop();
        int x = B.top().i;
        int y = A.top().i;
        int z = C.top().i;
        if (b[x] > b[z] - a[z] + a[y]) {
            v[x] = 2;
            ans += b[x];
            B.pop();
        }
        else {
            v[z] = 2;
            v[y] = 1;
            ans += b[z] - a[z] + a[y];
            A.pop();
            C.pop();
            C.push({b[y] - a[y], y});
        }
    }
    cout << ans << '\n';
    for (int i = 1; i <= n; ++i) {
        if (v[i] == 1) cout << i << ' ';
    }
    cout << '\n';
    for (int i = 1; i <= n; ++i) {
        if (v[i] == 2) cout << i << ' ';
    }
    cout << '\n';
    return 0;
}

Link