#include <cstring>
#include <iostream>
using namespace std;
int father[1001];
//初始化时表示各个点之间还没有边,,每个点就是一个集合
void unit(int n){
for(int i = 0 ; i <= n; i++){
father[i] = i;
}
}
int findRoot(int x){
//x是根
if(x == father[x]){
return x;
}else{
//找到x的根
return findRoot(father[x]);
}
}
void combine(int a , int b){
father[b] = a;
}
int main(){
int m , n , a , b;
while(cin >> n >> m && n != 0){
//初始化d 爹 数组
unit(n);
//m代表边的数量
for(int i = 1 ; i <= m ; i++){
cin >> a >> b;
//找到a b 的爹
int aRoot = findRoot(a);
int bRoot = findRoot(b);
//如果a的根与b的根不相同,就合并根
if(aRoot != bRoot)
combine(aRoot , bRoot);
}
//用于记录集合数量(我们知道 :n 个不联通子集最少添加 n - 1 条边 就会变成联通子集 ,即: 本题说的添加最少的公路)
int num = 0;
for(int i = 1 ; i <= n ; i ++){
if(father[i] == i)
++num;
}
cout << num - 1 << endl;
}
return 0;
}
HDU 1232
最新推荐文章于 2019-06-29 14:23:42 发布