b291中等

95 臺北市資訊學科能力競賽(2006)|用餐地點

選出總曼哈頓距離最小且座標字典序最小的用餐格。

解題思路

選出總曼哈頓距離最小且座標字典序最小的用餐格。

總成本可拆成橫列距離成本加直欄距離成本;各列及各欄的人數就是權重,因此兩軸可以獨立最小化。

由左往右移動一格,左側人群成本增加、右側減少;累積權重首次達總人數一半的索引即最小的加權中位數。

兩軸都選最左中位數,得到X最小再Y最小的最優點;全0人時選1,1。人數無上界,以大整數相加。

時間 O(mn),空間 O(m+n)個大整數;Python逐行讀入額外O(n),另計人數位數成本。

Step-by-step animation

分離兩軸的加權中位數逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

範例各列人數11、4、4,總19。

11
4
4
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
int main() {
    int m, n;
    cin >> m >> n;
    vector<cpp_int> r(m), c(n);
    cpp_int total = 0;
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++) {
            cpp_int x;
            cin >> x;
            r[i] += x;
            c[j] += x;
            total += x;
        }
    auto med = [&](vector<cpp_int> &v) {
        cpp_int sum = 0;
        for (int i = 0; i < (int)v.size(); i++) {
            sum += v[i];
            if (sum * 2 >= total)
                return i + 1;
        }
        return 1;
    };
    cout << med(r) << ' ' << med(c) << '\n';
}

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

更多