解題思路
把格子依高度由高到低排序,查詢水位也由高到低處理。
對每個查詢,啟用所有高度嚴格大於水位的格子;單格使平方和加 1,相鄰不同分量大小 a、b 合併時增加 (a+b)²-a²-b²=2ab。
啟用完成後,並查集分量恰是此水位的島嶼;依原查詢次序輸出保存的平方和。
設 V=hw,時間 O(V log V+q log q+(V+q)α(V)),空間 O(V+q)。
Step-by-step animation
教學例子:水位 3,範例最高格等於水位,沒有陸地。
步驟 1 / 3
步驟 1
水位 3,範例最高格等於水位,沒有陸地。
水
水
- 狀態
- 0
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int h, w, q;
cin >> h >> w >> q;
int n = h * w;
vector<long long> a(n), lev(q), ans(q);
for (auto &x : a)
cin >> x;
for (auto &x : lev)
cin >> x;
vector<int> ids(n), qs(q), p(n), sz(n, 1), on(n);
iota(ids.begin(), ids.end(), 0);
iota(qs.begin(), qs.end(), 0);
iota(p.begin(), p.end(), 0);
sort(ids.begin(), ids.end(), [&](int x, int y) { return a[x] > a[y]; });
sort(qs.begin(), qs.end(), [&](int x, int y) { return lev[x] > lev[y]; });
function<int(int)> find = [&](int x) { return p[x] == x ? x : p[x] = find(p[x]); };
long long s = 0;
int j = 0;
for (int k : qs) {
while (j < n && a[ids[j]] > lev[k]) {
int x = ids[j++];
on[x] = 1;
s++;
vector<int> nb;
if (x / w)
nb.push_back(x - w);
if (x / w + 1 < h)
nb.push_back(x + w);
if (x % w)
nb.push_back(x - 1);
if (x % w + 1 < w)
nb.push_back(x + 1);
for (int y : nb)
if (on[y]) {
int u = find(x), v = find(y);
if (u == v)
continue;
if (sz[u] < sz[v])
swap(u, v);
s += 2LL * sz[u] * sz[v];
p[v] = u;
sz[u] += sz[v];
}
}
ans[k] = s;
}
for (auto x : ans)
cout << x << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。