题解:P13716 [GCPC 2024] Alien Attack 2

· · 题解

题意

给定一张无向图,求最大连通块大小。

Solution

并查集维护即可,每次累加连通块大小并合并。要注意一定要在原祖先上累加合并,因为可能会加重。

代码里有注释。

Code

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

int n, m, fa[(int)2e5 + 5], ans = -INT_MAX, siz[(int)2e5 + 5];

int findd(int x) { // 查
    if (fa[x] != x) 
        fa[x] = findd(fa[x]);
    return fa[x];
}

void uni(int x, int y) { // 并
    fa[y] = x;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin >> n >> m;
    if (!m)  // 特判 m == 0
        return cout << 1, 0;
    for (int i = 1; i <= n; ++i) // 并查集初始化
        fa[i] = i, siz[i] = 1;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        cin >> x >> y;
        int r1 = findd(x), r2 = findd(y); // 一定要在原祖先上累加合并,因为可能会加重
        if (r1 == r2) // 如果已经在同一个连通块里就 continue
            continue;
        uni(r1, r2);
        siz[r1] += siz[r2]; // 累加连通块大小
        ans = max(ans, siz[r1]); // 统计答案
    }
    cout << ans;
    return 0;
}