解題思路
排序後,把最左和最右的門牌配成一對。選址位於這對門牌之間時,到兩者距離和等於其差;走到區間外只會增加成本。由外向內逐對分析,所有配對區間的交集包含中位數,因此中位數使總距離最小。
奇數人取中央門牌,偶數人取兩個中位門牌間任一位置皆可,程式直接取索引 r/2。逐一累加與中位數的絕對差,重複門牌也要分別計入。第一行是測試筆數,每筆只輸出距離總和,不輸出選址。
Step-by-step animation
示意:門牌 2,4,9
步驟 1 / 3
排序找中位數
中央門牌是 4。
2
4
9
- median
- 4
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a)
cin >> x;
sort(a.begin(), a.end());
long long total = 0;
for (int x : a)
total += abs(x - a[n / 2]);
cout << total << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。