POJ 1611 The Suspects(并查集,简单)

为什么ACM的题意都这么难懂,就不能说的直白点吗?还能不能好好的一起刷题了?

题意:你需要建一个n的并查集,有m个集合,最后要输出包含0的那个集合的元素的个数。

这是简单并查集应用,所以直接看代码吧!

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int INF=0x3f3f3f3f;
typedef long long ll;
typedef unsigned long long ull;
#define fi first
#define se second
#define prN printf("
")
#define SI(N) scanf("%d",&(N))
#define SII(N,M) scanf("%d%d",&(N),&(M))
#define SIII(N,M,K) scanf("%d%d%d",&(N),&(M),&(K))
#define cle(a,val) memset(a,(val),sizeof(a))
#define rep(i,b) for(int i=0;i<(b);i++)
#define Rep(i,a,b) for(int i=(a);i<=(b);i++)

int father[30005],mrank[30005];

void init(int n)
{
    int i;
    for (i=0;i<n;i++)
    {
        father[i]=i;//并查集是从零开始的
        mrank[i]=1;//mrank存的是集合中的个数
    }
}

int find_set(int x)
{
    if (x!=father[x])
    {
        father[x]=find_set(father[x]);
    }
    return father[x];
}

void myUnion(int x,int y)
{
    x=find_set(x);
    y=find_set(y);
    if (x==y) return;

    if (mrank[x]>=mrank[y])
    {
        father[y]=x;
        mrank[x]+=mrank[y];
    }
    else
    {
        father[x]=y;
        mrank[y]+=mrank[x];
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("C:\Users\Zmy\Desktop\in.txt","r",stdin);
//    freopen("C:\Users\Zmy\Desktop\out.txt","w",stdout);
#endif // ONLINE_JUDGE
    int n,m;
    while(cin>>n>>m,n||m)
    {
        init(n);
        int k,fi,se;
        for (int i=0;i<m;i++)
        {
            cin>>k>>fi;
            for (int j=1;j<k;j++)
            {
                cin>>se;
                myUnion(fi,se);
            }
        }
        cout<<mrank[father[0]]<<endl;
    }

    return 0;
}

  

原文地址:https://www.cnblogs.com/s1124yy/p/5520982.html