POJ 1611 (disjoint-set)

POJ1611

Title: multiple sets of input, to enter personal n, enter the m groups. Next, the first m lines each input k, k represent this group of individuals, k represents the number of the next member of the set of

Numbered 0 people may be sick, and sick groups of people may also may be sick, output n people how many people are probably sick

Ideas: disjoint-set line and, in each group who constitute a set, and their leader is the first person in each input, particularly when there may be sentenced to sick people in this group of people, let them become the head boss 0.

Finally, traversing about how many people's personal n is 0. output to head (head: Find (x) ,. boss: pre [x])

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <iomanip>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <vector>
//const int maxn = 1e5+5;
#define ll long long
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}

#define MAX INT_MAX
#define FOR(i,a,b) for( int i = a;i <= b;++i)
#define bug cout<<"--------------"<<endl
using namespace std;
int stu[31000],pre[31000];
int n,m,k,one,two;
int Find(int x)
{
    if(pre[x]==x) return  x;
    return Find(pre[x]);
}
void besame(int x,int y)
{
    int fx=Find(x);
    int fy=Find(y);
    if(fx!=fy) pre[fy]=fx;
}
void clearr()
{
    for(int i=0;i<n;++i)
        pre[i]=i;
}
int main()
{

    while(1)
    {
        cin>>n>>m;
        if(n==0&&m==0)
            break;
        clearr();
        while(m--)
        {
            cin>>k>>one;
            for(int i=1;i<k;++i)
            {
                cin>>two;
                if(Find(two)==0)
                {
                    besame(0,one);
                }
                else besame(one,two);
            }

        }
        int ans=0;
        FOR(i,0,n-1)
        {
            int hhh=Find(i);
            if(hhh==0)  ans++;
        }
        cost <<ans<<endl; 

    } 
}

 

Guess you like

Origin www.cnblogs.com/jrfr/p/11280114.html