P11231 [CSP-S 2024] 决斗

· · 题解

P11231 [CSP-S 2024] 决斗

题目链接

思路分析

提供一个赛时想出来的比较显然的解法。

如题,他让我们剩下来的最少,即就是被杀死的最多。那么,我们只需要不断地让 r 大的去杀 r 小的即可。

参考代码

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, cnt[N], maxn;
int main() {
    // freopen("duel.in", "r", stdin);
    // freopen("duel.out", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        int x; cin >> x;
        cnt[x]++;
        maxn = max(maxn, x);
    }
    for (int i = 1; i <= maxn; i++) {
        if (cnt[i] == 0) continue;
        int now = cnt[i];
        for (int j = 1; j < i; j++) {
            if (cnt[j] > now) {
                cnt[j] -= now;
                now = 0;
                break;
            } else {
                now -= cnt[j];
                cnt[j] = 0;
            }
        }
    }
    int res = 0;
    for (int i = 1; i <= maxn; i++) {
        res += cnt[i];
    }
    cout << res << endl;
    return 0;
}

时间复杂度

最坏 \mathcal{O}(n^2),但在随机数据下跑得飞快(指洛谷民间数据),但要卡的话也能卡掉。