跳到正文

题解

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

Jason_wzc约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年8月17日
收录
2026年8月19日
更新
2026年8月19日
篇幅
约 4 分钟

版本

  1. v1当前

题解:ARC227 - A

题面:Fermat Point of Binary Strings。

解题思路

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

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

令 A,B,C,XA, B, C, X 中第 ii 个 11 的位置为 pai,pbi,pci,pxipa_i, pb_i, pc_i, px_i,则答案为:

dist(A,X)+dist(B,X)+dist(C,X)=∑i=1N(∣pai−pxi∣+∣pbi−pxi∣+∣pci−pxi∣)\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≤2×105N \leq 2 \times 10^5,所以直接遍历 i=1∼Ni = 1 \sim N 然后求 ∣pai−pxi∣+∣pbi−pxi∣+∣pci−pxi∣|pa_i - px_i| + |pb_i - px_i| + |pc_i - px_i| 的值就可以了。

根据绝对值的性质,显然 pxipx_i 取 pai,pbi,pcipa_i, pb_i, pc_i 的中位数就可以了。

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

时间复杂度为 O(N)O(N)。

代码实现

C++
#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;
}
原文