使用并查集,套用基本模板即可。
#include <iostream>
using namespace std;
const int MAXN = 1005;
int father[MAXN]; //父结点
//初始化并查集
void makeSet(int n)
{
for (int i = 1; i <= n; i++)
father[i] = i;
}
//查找x所在集合的代表元素(所在树的根结点)
int find(int x)
{
if (x != father[x])
father[x] = find(father[x]);
return father[x];
}
//合并x所在集合和y所在集合
void unionSet(int x, int y)
{
int fx = find(x);
int fy = find(y);
if (fx != fy)
father[fx] = fy;
}
int main()
{
int N, M;
while (cin >> N)
{
if (N == 0)
break;
cin >> M;
makeSet(N);
int A, B;
for (int i = 0; i < M; i++)
{
cin >> A >> B;
unionSet(A, B);
}
int road = 0; //修路数量
for (int i = 1; i <= N; i++)
{
if (i == father[i])
++road;
}
cout << --road << endl;
}
return 0;
}
继续加油。