a576中等相反順序配對的交換論證

CPE:The Bus Driver Problem (UVa 11389)

讓短早班搭配長晚班,平衡超時的總成本。

前往題目練習 →回報教學錯誤時間 O(n log n),空間 O(n)。

解題思路

把早班由短到長排、晚班由長到短排,再逐對計算max(0,早+晚−d)×r。這種配對把大工作量互相分散,避免兩條長路線擠在同一人身上,而另一人工作量仍未超過門檻。

令a≤b、x≤y,超時函數f(t)=max(0,t−d)是凸的,故f(a+x)+f(b+y)≥f(a+y)+f(b+x)。交換同向配對為反向配對不會增加成本,反覆交換後即可得到排序方案,因此它達到全域最小。0 0 0結束,不能把所有長度總和減nd後直接當超時量。

Step-by-step animation

示意:早班5、15,晚班5、15,d=20、r=2

回報動畫錯誤
步驟 1 / 3

同向配對

5+5=10不超時,15+15=30超時10,費用20。

10→0
30→20
總費用
20

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

int main() {
    int n, d, r;
    while (cin >> n >> d >> r && (n || d || r)) {
        vector<int> a(n), b(n);
        for (int &x : a)
            cin >> x;
        for (int &x : b)
            cin >> x;
        sort(a.begin(), a.end());
        sort(b.rbegin(), b.rend());
        long long ans = 0;
        for (int i = 0; i < n; ++i)
            ans += 1LL * max(0, a[i] + b[i] - d) * r;
        cout << ans << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多