hdu 畅通工程1232

#include <stdio.h>
#include <string.h>
#define N 1001

int ufs[N];
int rank[N];
bool rec[N];

int getFather(int n){
if(ufs[n]!=n) ufs[n]=getFather(ufs[n]);
return ufs[n];
}

int merge(int a, int b){
int ta=getFather(a) ;
int tb=getFather(b) ;
if(ta != tb)
ufs[ta] = tb;

return 0;
}

void count(int n){
int i;
int count=0;
for (i = 0 ;i <=n ;i ++) // 1 - n
{
// printf( "{%d}\n",getFather(i));
rec[getFather(i)]=1;
}

for ( i = 1 ;i <=n ;i ++)
{
//printf("{%d}",rec[i]);

if(rec[i])count++;
}
printf("%d\n",count-1);

}


int main(){

int n,m;
int tempa,tempb;
// freopen("input.txt","r",stdin);
while(scanf("%d",&n)&&n){
memset(ufs,0,sizeof(ufs));
memset(rec,0,sizeof(rec));
int i;
scanf("%d",&m);
for (i = 0 ;i <=n ;i ++)
{
ufs[i]=i;
}
for ( i = 0 ;i < m ;i ++)
{
scanf("%d %d",&tempa,&tempb);
merge(tempa,tempb);
}
count(n);

}
return 0;

}



原文地址:https://www.cnblogs.com/lfzark/p/2424028.html