题解:AT_abc474_e One Time Coupon

· · 题解

我们考虑哪些商品使用优惠券会比较优。对第 i 个物品使用优惠券会省下 a_i - b_i 元,因此按 a_i - b_i 升序排序。

枚举一个后缀全都用优惠券,然后前面的商品正常买会给后缀提供优惠券。我们前面的商品先每种只买一次,如果优惠券还是不够就从前面的商品中挑一个 a_i 最小的一直买直到优惠券凑够为止。

有人可能问为什么不是从全局挑 a_i 最小,原因是如果你在一直买的那个商品前面的商品如果使用了优惠券一定是不优的,原因是对于 i>j,a_i > a_i - b_i > a_j - b_j,因此取前缀 a_i 最小就是对的,这同时也证明了排序后选优惠券的一定是一个连续后缀。

:::success[CODE]

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int maxn = 2e+5 + 5, inf = 1e17;
int T, n;
int pre[maxn], suf[maxn];
struct V {
    int a, b;
}c[maxn];
inline void GOGOGO() {
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> c[i].a >> c[i].b;
    sort(c + 1, c + n + 1, [](V x, V y){return x.a - x.b < y.a - y.b;});
    for (int i = 1; i <= n; i++) pre[i] = pre[i - 1] + c[i].a;
    suf[n + 1] = 0;
    for (int i = n; i; i--) suf[i] = suf[i + 1] + c[i].b;
    int mn = inf, ans = inf;
    for (int i = 1; i <= n; i++) {
        mn = min(mn, c[i].a);
        int res = pre[i] + suf[i + 1], dt = max(0ll, (n - i) - i);
        res += mn * dt;
        ans = min(ans, res);
    }
    cout << ans << '\n';
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> T;
    while (T--) GOGOGO();
    return 0;
}

::: 欢迎找错,欢迎 hack。