HDU 1232 畅通工程

HDU_1232

    直接应用并查集,然后再统计一共有多少组节点即可。

#include<stdio.h>
#include<string.h>
int p[1010],hash[1010];
int find(int x)
{
return p[x]==x?x:(p[x]=find(p[x]));
}
int main()
{
int i,j,x,y,tx,ty,N,M,ans;
while(1)
{
scanf("%d",&N);
if(N==0)
break;
scanf("%d",&M);
for(i=1;i<=N;i++)
p[i]=i;
for(i=0;i<M;i++)
{
scanf("%d%d",&x,&y);
if(find(x)!=find(y))
p[find(x)]=find(y);
}
ans=0;
memset(hash,0,sizeof(hash));
for(i=1;i<=N;i++)
hash[find(i)]=1;
for(i=1;i<=N;i++)
ans+=hash[i];
ans--;
printf("%d\n",ans);
}
return 0;
}


原文地址:https://www.cnblogs.com/staginner/p/2189769.html