您的位置:首页 > 其它

zoj 1789 The Suspects

2012-02-04 15:34 369 查看
/*
zoj_1789    并查集
并查集的简单应用,可以继续优化。
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <string.h>
#define N 30002
using namespace std;
int father
,num
,h
;

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: