1 条题解

  • 0
    @ 2056-6-7 9:52:04

    【例54.2】 学生组队

    解题思路

    把能力升序排序,相邻两人组成一队,只提升较低者到较高者,费用是差值,累计第0/1、2/3……对。

    正确性说明

    在数轴上,若配对交叉或嵌套,改成两组相邻配对不会增加两段距离之和。反复消去非相邻配对可得相邻配对最优,费用为这些相邻差之和。

    易错点

    只能提升不能降低,单对最省是把小者补到大者。

    复杂度

    时间O(n log n),空间O(n)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        vector<long long> a(n);
        for (auto &x : a)
            cin >> x;
        sort(a.begin(), a.end());
        long long ans = 0;
        for (int i = 0; i < n; i += 2)
            ans += a[i + 1] - a[i];
        cout << ans << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    358
    时间
    1000ms
    内存
    64MiB
    难度
    普及−
    标签
    递交数
    0
    已通过
    0
    上传者