题解:【ARC227】A - Fermat Point of Binary Strings

· · 题解

题解:ARC227 - A

题面:Fermat Point of Binary Strings。

解题思路

首先转化一下 \text{dist}(S, T) 这个值,令 S 中第 i 个 1 的位置为 ps_i,T 中的为 pt_i,首先交换相同的数字肯定是没有意义的,因此累加到交换次数中的只会有交换 0 和 1 的操作;又因为 |ps_{i - 1} - pt_{i}| + |ps_{i} - pt_{i - 1}| > |ps_{i - 1} - pt_{i - 1}| + |ps_{i} - pt_{i}|,所以将每个第 i 个 1 从 S 移到 T 能保证最小。

因此 \text{dist}(S, T) = \sum_{i = 1}^{N} |ps_i - pt_i|。

令 A, B, C, X 中第 i 个 1 的位置为 pa_i, pb_i, pc_i, px_i,则答案为:

\text{dist}(A, X) + \text{dist}(B, X) + \text{dist}(C, X) = \sum_{i = 1}^{N} (|pa_i - px_i| + |pb_i - px_i| + |pc_i - px_i|)

因为 N \leq 2 \times 10^5,所以直接遍历 i = 1 \sim N 然后求 |pa_i - px_i| + |pb_i - px_i| + |pc_i - px_i| 的值就可以了。

根据绝对值的性质,显然 px_i 取 pa_i, pb_i, pc_i 的中位数就可以了。

在处理好 px_i 后,直接根据这个反推出答案 X 的值。

时间复杂度为 O(N)。

代码实现

#include <iostream>
#include <vector>
#include <algorithm>
#include <array>
#include <atcoder/all>
#define endl '\n'
using namespace std;
typedef long long ll;

int main(int argc, char* argv[]) {
    // freopen(".in", "r", stdin);
    // freopen(".out", "w", stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);

    int n;
    cin >> n;
    array<string, 3> a;
    for (auto& p : a) {
        cin >> p;
    }
    array<vector<int>, 3> res; // res[0] ~ res[2] 对应 pa, pb, pc
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < n * 2; j++) {
            if (a[i][j] == '1') {
                res[i].push_back(j);
            }
        }
    }
    ll k = 0; string x(n * 2, '0'); // 答案
    for (int i = 0; i < n; i++) {
        array<int, 3> cur = { res[0][i], res[1][i], res[2][i] };
        sort(cur.begin(), cur.end()); // 排序后 cur[1] 就是中位数
        for (int j = 0; j < 3; j++) {
            k += llabs(cur[1] - res[j][i]);
        }
        x[cur[1]] = '1'; // 反推 X
    }
    cout << k << endl;
    cout << x << endl;
    return 0;
}