解題思路
展平成V=N²個位置。設高度t後,下一個起查位置為(pos+t)%V;使用後繼DSU找該位置之後首個未填格,越過V則回到find(0)。填格後把它指向下一個未填格。
保存每個高度所在位置。由最高高度往最低處理,每格若有較低鄰居,就把所有球交給高度最低的那一格。因目的高度更低,它還未處理,所以會繼續向下傳遞。
所有高度相異,最低鄰居唯一,球最終停在局部極小值;最後計數非零球格與最大球數。這等價於逐球完整滾動,但每格只處理一次。
時間 O(Vα(V)),盤面、後繼DSU、位置與球數O(V),Python輸入O(1)。
Step-by-step animation
循環後繼DSU與高度順序傳遞|N=2起點(0,0),高度1先放左上。
步驟 1 / 3
填第一格
N=2起點(0,0),高度1先放左上。
1
?
?
?
- t
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, r, c;
cin >> n >> r >> c;
int V = n * n;
vector<int> p(V + 1), h(V), pos(V + 1), balls(V, 1);
iota(p.begin(), p.end(), 0);
auto find = [&](int x) {
int y = x;
while (p[y] != y)
y = p[y];
while (p[x] != x) {
int z = p[x];
p[x] = y;
x = z;
}
return y;
};
int u = r * n + c;
for (int t = 1; t <= V; t++) {
h[u] = t;
pos[t] = u;
p[u] = find(u + 1);
if (t < V) {
u = find((u + t) % V);
if (u == V)
u = find(0);
}
}
for (int t = V; t >= 1; t--) {
int u = pos[t], x = u / n, y = u % n, b = u;
for (auto [dx, dy] : vector<pair<int, int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) {
int a = x + dx, c = y + dy;
if (a >= 0 && a < n && c >= 0 && c < n && h[a * n + c] < h[b])
b = a * n + c;
}
if (b != u) {
balls[b] += balls[u];
balls[u] = 0;
}
}
int cnt = 0, best = 0;
for (int x : balls)
if (x) {
cnt++;
best = max(best, x);
}
cout << cnt << " " << best << "\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。