b337中等

94 臺北市資訊學科能力競賽(2005)|聚集問題

求門檻距離內相連的所有聚集大小。

解題思路

求門檻距離內相連的所有聚集大小。

依兩條整數模遞迴產生B個座標,重疊點仍保留為不同索引。

枚舉每對點,若(dx)²+(dy)²≤C²就合併兩索引的並查集,不需浮點開根號。

連通分量正是經過若干相鄰點可到達的聚集;最後統計每個根的大小並排序,輸出分量數與完整大小清單。

每筆時間 O(B² α(B))、工作空間 O(B),B≤4000。Python一次split另用 O(q)保留全部q筆參數;並查集路徑壓縮不需深層遞迴。

Step-by-step animation

產生座標後的距離連通分量逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

A=1,B=3產生(74,90),(38,56),(36,57)。

三點
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int A, B, C;
    while (cin >> A >> B >> C) {
        vector<pair<int, int>> a;
        int x = A, y = A;
        for (int i = 0; i < B; i++) {
            x = (269 * x + 11) % 103;
            y = (271 * y + 13) % 97;
            a.push_back({x, y});
        }
        vector<int> p(B), sz(B, 1);
        iota(p.begin(), p.end(), 0);
        function<int(int)> find = [&](int u) {
            while (p[u] != u) {
                p[u] = p[p[u]];
                u = p[u];
            }
            return u;
        };
        for (int i = 0; i < B; i++)
            for (int j = 0; j < i; j++) {
                int dx = a[i].first - a[j].first, dy = a[i].second - a[j].second;
                if (dx * dx + dy * dy <= C * C) {
                    int u = find(i), v = find(j);
                    if (u != v) {
                        if (sz[u] < sz[v])
                            swap(u, v);
                        p[v] = u;
                        sz[u] += sz[v];
                    }
                }
            }
        vector<int> ans;
        for (int i = 0; i < B; i++)
            if (find(i) == i)
                ans.push_back(sz[i]);
        sort(ans.begin(), ans.end());
        cout << ans.size() << '\n';
        for (int i = 0; i < (int)ans.size(); i++)
            cout << (i ? " " : "") << ans[i];
        cout << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多