UVa – 10583 – Ubiquitous Religions

Problem Link: https://onlinejudge.org/external/105/10583.pdf

Note: This is a straightforward application of the Union-Find(Disjoint Set) algorithm.

Code:

#include <bits/stdc++.h>

using namespace std;

int Find(int x, vector<int> &root)
{
    if(x==root[x]) return x;
    return root[x]=Find(root[x], root);
}

void Union(int x, int y, vector<int> &root, vector<int> &ranking)
{
    int rootX=Find(x, root);
    int rootY=Find(y, root);
    if(rootX!=rootY)
    {
        if(ranking[rootX]>=ranking[rootY])
        {
            root[rootY]=rootX;
            ranking[rootX]+=ranking[rootY];
        }
        else
        {
            root[rootX]=rootY;
            ranking[rootY]+=ranking[rootX];
        }
    }
}

int main()
{
//    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
    int n,m, t=1;
    while(cin>>n>>m)
    {
        if(n==0 && m==0) break;
        vector<int> root(n+1), ranking(n+1);
        for(int i=1; i<=n; i++)
        {
            root[i]=i;
            ranking[i]=1;
        }
        for(int i=0; i<m; i++)
        {
            int x,y;
            cin>>x>>y;
            Union(x,y, root, ranking);
        }
        int ans=0;
        for(int i=1; i<=n; i++)
        {
            if(root[i]==i) ans++;
        }
        cout<<"Case "<<t<<": "<<ans<<endl;
        t++;
    }
    return 0;
}

One thought on “UVa – 10583 – Ubiquitous Religions

Leave a comment