并查集专题练习(一)POJ1611

来源:互联网 发布:chrome js秒杀 编辑:程序博客网 时间:2024/06/08 06:19
//最开始的时候..在最后直接比较father[0]和father[i]一直都没有正确
//后来改成了比较find_set(0)和find_set(i)才正确了..
//以后要注意这一点..其实这样去把每个点都更新一次..花不了多少时间的...
//但是如果有某些点没有更新到的话.直接用father就会导致错误
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
int father[33333],rank[33333],a[33333];
void make_set(int x)
{
    father[x] = x;
    rank[x] = 0;
}
int find_set(int x)
{
   if(x != father[x])
   {
       father[x] = find_set(father[x]);
   }
   return father[x];
}
void Union(int x , int y)
{
    int x1 = find_set(x);
    int y1 = find_set(y);
    if(x1 == y1)return;
    else
    {
        if(rank[x1] > rank[y1])
        {
            father[y1] = x1;
            find_set(y);
        }
        else
        {
            if(rank[x1] == rank[y1])
              rank[y1]++;
            father[x1] = y1;
            find_set(x);
        }
    }
}
int main()
{
    int m,n;
    while(scanf("%d%d",&n,&m) && n + m != 0)
    {
        for(int i = 0 ; i < n ; i++)make_set(i);
        for(int i = 1 ; i <= m ; i++)
        {
            int num;
            scanf("%d",&num);
            for(int j = 1 ; j <= num ; j++)
            {
                scanf("%d",&a[j]);
                if(j != 1)
                {
                    Union(a[j],a[j-1]);
                }
            }
        }
        int ans = 0;
        int b = find_set(0);
        for(int i = 0 ; i < n ; i++)
        {
            if(find_set(i) == b)ans++;
        }
        printf("%d\n",ans);
    }
}
原创粉丝点击