#include <iostream>
#include <string>
#include <vector>
using namespace std;
int father[1001];
int res;
int find(int x)
{
int r = x;
while (father[r] != r)
r = father[r];
int i = x, j;
while (i != r)
{
j = father[i];
father[i] = r;
i = j;
}
return r;
}
void join(int x, int y) {
int fx = find(x), fy = find(y);
if (fx != fy) {
father[fx] = fy;
res--;
}
}
int main()
{
int n;
int m;
int s;
int t;
cin >> n >> m;
res = n - 1;
for (int i = 1; i < n + 1; i++)
{
father[i] = i;
}
for (int i = 0; i < m; i++)
{
cin >> s >> t;
join(s, t);
}
cout << res;
}
参考链接
并查集