题解归档 - cf104118J

题解归档 - cf104118J

本文由 cf-code 本地题解库自动归档;公开内容以本地 AC/验证版本为准。

思路

Gym 104118J - Junior Steiner Three

There are exactly three land cells. In a grid with 4-neighbor movement, the minimum rectilinear Steiner tree for three terminals is obtained by connecting all three to a coordinate-wise median point.

Let (cx, cy) be the median of the three row coordinates and the median of the three column coordinates. Paint any Manhattan path from each original land cell to (cx, cy). The union is connected, keeps all original land cells, and has minimum possible number of added cells.

Complexity: O(r c).

Checks:

  • sample 1 shape differs from sample output but has the same optimal size/connectivity

代码

来源:problems/cf104118J/solution.cpp

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int r, c;
    cin >> r >> c;
    vector<string> g(r);
    for (auto &s : g) cin >> s;

    vector<pair<int, int>> p;
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < c; ++j) {
            if (g[i][j] == '#') p.push_back({i, j});
        }
    }

    vector<int> xs, ys;
    for (auto [x, y] : p) {
        xs.push_back(x);
        ys.push_back(y);
    }
    sort(xs.begin(), xs.end());
    sort(ys.begin(), ys.end());
    int cx = xs[1], cy = ys[1];

    auto paint = [&](int x, int y) {
        while (x != cx) {
            g[x][y] = '#';
            x += (x < cx ? 1 : -1);
        }
        while (y != cy) {
            g[x][y] = '#';
            y += (y < cy ? 1 : -1);
        }
        g[x][y] = '#';
    };

    for (auto [x, y] : p) paint(x, y);

    for (auto &s : g) cout << s << '\n';
    return 0;
}
~  ~  The   End  ~  ~


 赏 
感谢您的支持,我会继续努力哒!
支付宝收款码
tips
文章二维码 分类标签:归档TypechoAutoUpload
文章标题:题解归档 - cf104118J
文章链接:https://www.fangshaonian.cn/archives/174/
最后编辑:2026 年 6 月 28 日 19:03 By 方少年
许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
(*) 6 + 5 =
快来做第一个评论的人吧~