标签:
4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
1 0 2 998Huge input, scanf is recommended.HintHint
#include<cstdio>
int a[10000];
int find(int x)//查找x元所属的集合。
{
int r = x;
while (r != a[r])
r = a[r];
return r;
}
void unio(int x, int y)
{
int fx, fy;
fx = find(x);
fy = find(y);
if (a[fx] != fy)//如果不在一个集合那么将这两个集合合并。
a[fx] = fy;//或者写为a[fy]=fx;
}
int main()
{
int n, m,x,y;
while (~scanf("%d", &n) && n)
{
int ans = -1;
for (int i = 1; i <= n; i++)
a[i] = i;
scanf("%d", &m);
while (m--)
{
scanf("%d%d", &x, &y);
unio(x, y);
}
for (int i = 1; i <= n; i++)
{
if (a[i] == i)
ans++;
}
printf("%d\n", ans);
}
return 0;
}标签:
原文地址:http://blog.csdn.net/qq_24489717/article/details/45949929