POJ 1611 : The Suspects (普通并查集)

思路:

模板题,一步一步加入集合,最后判断有多少人跟0在同一个集合就行了。

#include<iostream>
#include<cstdio>
using namespace std;
const int manx = 3e4 + 5;
int a[manx];
int find(int x){
    return a[x] == x ? x : a[x] = find(a[x]);
}
int main()
{
    int n, m, u, v;
    while (cin >> n >> m){
        if (n == 0 && m == 0) break;
        for (int i = 0; i < n; i++) a[i] = i;
        while (m--){
            int q;
            cin >> q >> u;
            for (int i = 1; i < q; i++) {
                cin >> v;
                a[find(u)] = find(v);
                u = v;
            }
        }
        int ans = 0;
        for (int i = 0; i < n; i++)
            if (find(a[i]) == find(0))
                ans++;
        cout << ans << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/RioTian/p/13080860.html