poj 2524 Ubiquitous Religions

并查集

#include <cstdio>
#include <vector>
using namespace std;

/**
 * Disjoint Set Union
 */
class DSU
{
    vector<int> s;
    int cnt;
 public:
    DSU(int n) {
        cnt = n;
        s.resize(n+1);
        for (int i = 1; i <= n; ++i) s[i] = i;
    }
    int find(int x) {
        if (x != s[x]) s[x] = find(s[x]);
        return s[x];
    }
    bool unite(int u, int v) {
        int x = find(u);
        int y = find(v);
        if (x != y) {
            s[y] = x;
            --cnt;
            return true;
        }
        return false;
    }
    int getCnt() {
        return cnt;
    }
};
int main()
{
    int n, m;
    for (int cas = 1; ~scanf("%d%d", &n, &m) && (n|m); ++cas) {
        DSU dsu(n);
        while (m--) {
            int i, j;
            scanf("%d%d", &i, &j);
            dsu.unite(i, j);
        }
        printf("Case %d: %d\n", cas, dsu.getCnt());
    }
    return 0;
}

posted @ 2021-02-28 21:28  Zewbie  阅读(38)  评论(0)    收藏  举报