| Time Limit: 2000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
Input
Output
Sample Input
4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
Sample Output
1 0 2 998
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 1010;
int parent[MAXN];
int n, m;
void make_set()
{
for (int i = 0; i <= n; i++)
parent[i] = -1;
}
int find_set(int t)
{
if (parent[t] == -1)
return t;
else
return parent[t]=find_set(parent[t]);
}
void union_set(int a, int b)
{
int t1 = find_set(a);
int t2 = find_set(b);
if (t1 != t2)
parent[t2] = t1;
}
int main()
{
int a, b;
while (scanf("%d", &n) != EOF&&n)
{
scanf("%d", &m);
make_set();
for (int i = 0; i < m; i++)
{
scanf("%d%d", &a, &b);
union_set(a, b);
}
int sum = 0;
for (int i = 1; i <= n;i++)
if (parent[i] == -1)
sum++;
printf("%d\n", sum-1);
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/qq_18738333/article/details/47977711