解題思路
把計程車與路人座標分別升序排序。對a≤b及c≤d,有|a−c|+|b−d|≤|a−d|+|b−c|。
因此若配對有逆序,交換兩位路人的車輛指派不會增加距離。反覆交換後得到相同排名互配的最優解。
加總各排名座標差的絕對值,總和最大可達兆等級,C++用64位元。
時間 O(m log m),儲存 O(m)。
Step-by-step animation
排序配對的交換論證|車在1,10,路人在2,9。
步驟 1 / 3
排序
車在1,10,路人在2,9。
車1
車10
人2
人9
- 配對
- 同排名
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
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.begin(), b.end());
long long ans = 0;
for (int i = 0; i < n; i++)
ans += abs(a[i] - b[i]);
cout << ans << "\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。