You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
#include <bits/stdc++.h>
|
|
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
int n;//城镇数目
|
|
|
|
|
int m;//道路数目
|
|
|
|
|
int x, y; //城镇的编号
|
|
|
|
|
|
|
|
|
|
const int N = 1010;
|
|
|
|
|
int fa[N]; //并查集数组
|
|
|
|
|
|
|
|
|
|
//要深入理解这个递归并压缩的过程
|
|
|
|
|
int find(int x) {
|
|
|
|
|
if (fa[x] != x) fa[x] = find(fa[x]);
|
|
|
|
|
return fa[x];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//加入家族集合中
|
|
|
|
|
void join(int c1, int c2) {
|
|
|
|
|
int f1 = find(c1), f2 = find(c2);
|
|
|
|
|
if (f1 != f2)fa[f1] = f2;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
//输入包含若干组测试数据
|
|
|
|
|
while (cin >> n) {
|
|
|
|
|
if (n == 0) break; //读取到0是退出条件,这个可以做为标准用例,强行记下即可
|
|
|
|
|
|
|
|
|
|
cin >> m;
|
|
|
|
|
//并查集初始化
|
|
|
|
|
for (int i = 1; i <= n; i++)fa[i] = i;
|
|
|
|
|
|
|
|
|
|
//填充并查集
|
|
|
|
|
for (int i = 1; i <= m; i++) {
|
|
|
|
|
cin >> x >> y;
|
|
|
|
|
join(x, y);
|
|
|
|
|
}
|
|
|
|
|
//剩余几个集合呢?
|
|
|
|
|
int cnt = 0; //这里有并查集的一个查询技巧,可以通过fa[i]==i知道具体有多少个最终的集合。
|
|
|
|
|
for (int i = 1; i <= n; i++) if (fa[i] == i) cnt++;
|
|
|
|
|
cout << cnt - 1 << endl;
|
|
|
|
|
}
|
|
|
|
|
return 0;
|
|
|
|
|
}
|