zoj 1789 The Suspects
来源:互联网 发布:靠谱的理财产品 知乎 编辑:程序博客网 时间:2024/06/07 18:27
/*zoj_1789 并查集并查集的简单应用,可以继续优化。*/#include <iostream>#include <cstdio>#include <vector>#include <string.h>#define N 30002using namespace std;int father[N],num[N],h[N];void init( int n ){ int i; for( i=0;i<n;i++ ) father[i]=i , h[i]=0 ;}int find_set( int a ){ if( a!=father[a] ) { father[a]=find_set(father[a]); } return father[a];}void union_set( int a,int b ){ if( a==b ) return; if( h[a]>h[b] ) father[b]=a; else { if( h[a]==h[b] ) h[b]++; father[a]=b; }}int main(){ int n,m,k,i,j,co; while( scanf( "%d%d",&n,&m ) && (n || m) ) { init(n); while( m-- ) { scanf( "%d",&k ); for( i=0;i<k;i++ ) scanf( "%d",&num[i] ); for( i=0;i<k;i++ ) for( j=i+1;j<k;j++ ) union_set( find_set( num[i] ),find_set( num[j] ) ); } co=0; for( i=0;i<n;i++ ) find_set(i); for( i=0;i<n;i++ ) if( father[i]==father[0] ) co++; printf( "%d\n",co ); } return 0;}