解題思路
每格是頂點,只建立向右、向下的相鄰邊,權重是高度差絕對值。按權重遞增合併兩端分量,並維護分量大小。
處理完權重不超過 K 的邊後,並查集恰等於拖拉機成本 K 能互達的區塊。第一個大小達到 (N²+1)//2 的時刻就是答案;此前沒有起點能走訪足夠多格。N=1 時不需跨邊,答案為 0。
令 V=N²、E=2N(N−1),時間 O(E log E),空間 O(V+E)。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。
Step-by-step animation
教學示意(以步驟描述中的輸入為準)
步驟 1 / 3
建立高度圖
示意 2×2 高度:0 2 / 5 8。
0
2
5
8
- 目標格數
- 2
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int v = n * n;
vector<int> a(v), p(v), sz(v, 1);
for (auto &x : a)
cin >> x;
iota(p.begin(), p.end(), 0);
vector<array<int, 3>> e;
for (int i = 0; i < v; i++) {
if (i % n + 1 < n)
e.push_back({abs(a[i] - a[i + 1]), i, i + 1});
if (i + n < v)
e.push_back({abs(a[i] - a[i + n]), i, i + n});
}
sort(e.begin(), e.end());
auto find = [&](int x) {
while (x != p[x])
x = p[x] = p[p[x]];
return x;
};
int ans = 0, need = (v + 1) / 2;
if (need > 1)
for (auto [w, u, t] : e) {
u = find(u);
t = find(t);
if (u == t)
continue;
if (sz[u] < sz[t])
swap(u, t);
p[t] = u;
sz[u] += sz[t];
if (sz[u] >= need) {
ans = w;
break;
}
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。