【題解】AtCoder ABC 177D – Friends

【題目敘述】https://atcoder.jp/contests/abc177/tasks/abc177_d
【解題想法】並查集

#include <iostream>
#include <cstring>
using namespace std;

int n, m, p[200005], ans = 1;

int pa(int x){
    if (p[x] < 0) return x;
    return p[x] = pa(p[x]);
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> m;
    memset(p, -1, sizeof(p));
    for (int i = 0, a, b; i < m; i++){
        cin >> a >> b;
        int x = pa(a), y = pa(b);
        if (x != y){
            p[x] += p[y];
            p[y] = x;
            ans = max(ans, -p[x]);
        }
    }
    cout << ans << "\n";
}

分享本文 Share with friends