Problem-1232 畅通工程

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值