Problem-1232 畅通工程
题目入口:
http://acm.hdu.edu.cn/showproblem.php?pid=1232
我的想法
并查集讲解:
https://blog.csdn.net/niushuai666/article/details/6662911
https://blog.csdn.net/liujian20150808/article/details/50848646
学习了并查集后的第一题试炼
注意从一编号
AC代码
#include <iostream>
#include <cstdio>
using namespace std;
int pre[1010]; //存放上级
int find(int x){ //寻找最大祖先
int r = x;
while (pre[r] != r) r = pre[r];
int i = x, j;
while (i != r){
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
int join(int x, int y){ //合并连通分支
int judge = 0;
int fx = find(x), fy = find(y);
if (fx != fy){ //判断两个连通分支是否有共同祖先
pre[fx] = fy;
judge = 1;
}
return judge; //两座城市之间是否连通
}
int main() {
int cities, roads, a, b, total;
while (scanf("%d%d", &cities, &roads) && cities){ //多组样例
total = cities - 1; //初始有cities-1个路要修
for (int i = 1; i <= cities; i++) pre[i] = i;
for (int i = 0; i < roads; i++){
scanf("%d%d", &a, &b);
if (join(a, b)) total--; //合并两个连通分支少修一条路
}
printf("%d\n", total); //最少修路数
}
return 0;
}