题意:求包含0元素的集合的元素个数
题解:基础并查集
#include <stdio.h>
#include <iostream>
using namespace std ;
#define MAX 30005
int parent[MAX] ;
int rank[MAX] ;
int num[MAX] ;
void make_set(int x)
{parent[x] = x ;rank[x] = 0 ;num[x] = 1 ;
}
int find_set(int x)//查找x的根节点
{int r = x , temp ;while(parent[r] != r) r = parent[r] ;while(x != r){temp = parent[x] ;parent[x] = r ;x = temp ;}return x ;
}
void union_set(int x , int y)//合并两个集合
{x = find_set(x) ;y = find_set(y) ;if(x == y) return ;if(rank[x] > rank[y]){parent[y] = x ;num[x] += num[y] ;}else{parent[x] = y ;if(rank[x] == rank[y]) rank[y] ++ ;num[y] += num[x] ;}
}
int main()
{int m , n , t , x , y;while(scanf("%d%d",&n , &m)!= EOF , m+n){if(m == 0){cout << '1' << endl ;continue ;}for(int i = 0 ; i < n ; i ++) make_set(i) ;for(int i = 0 ; i < m ; i ++){scanf("%d" , &t) ;scanf("%d" , &x) ;for (int j = 1; j < t; ++j){scanf("%d" , &y) ;union_set(x , y) ;x = y ;}}x = find_set(0) ;cout << num[x] << endl ;}return 0 ;
}