hdu 1232 畅通project

时间:2021-12-27 03:32:36

题目:

链接:点击打开链接

算法:

赤裸裸的并查集。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std; int n,m;
int root[1010]; int find(int x)
{
int r = x;
while(root[r] != r)
r = root[r];
return r;
} void merge(int x,int y)
{
int fx = find(x);
int fy = find(y);
if(fx != fy)
root[fx] = fy;
} int main()
{
//freopen("input.txt","r",stdin);
int a,b;
int cnt;
while(scanf("%d",&n) != EOF && n)
{
memset(root,0,sizeof(root));
for(int i=1; i<=n; i++)
root[i] = i;
scanf("%d",&m);
for(int i=1; i<=m; i++)
{
scanf("%d%d",&a,&b);
merge(a,b);
}
cnt = -1;
for(int i=1; i<=n; i++)
{
if(root[i] == i)
cnt++;
}
printf("%d\n",cnt);
}
return 0;
}