题解 | #畅通工程#

畅通工程

https://www.nowcoder.com/practice/4878e6c6a24e443aac5211d194cf3913

//并查集或者BFS,DFS求有几个连通分量
#include<iostream>
#include<set>
using namespace std;

int father[1200];

int findFather(int x) {
    if (x == father[x]) {
        return x;
    } else {
        father[x] = findFather(father[x]);
        return father[x];
    }
}

void mergeUnion(int x, int y) {
    int x_father = findFather(x);
    int y_father = findFather(y);
    father[y_father] = father[x];
}
int main() {
    int N, M;
    while (scanf("%d", &N) != EOF) {
        if (N == 0) {
            break;
        }
        for (int i = 0; i < 1200; i++) {
            father[i] = i;
        }
        scanf("%d", &M);
        while (M--) {
            int a, b;
            scanf("%d %d", &a, &b);
            mergeUnion(a, b);
        }
        set<int>blocks;
        for (int i = 1; i <= N; i++) {
            blocks.insert(findFather(i));
        }
        printf("%d\n", blocks.size() - 1);
    }
}

全部评论

相关推荐

10-24 13:36
门头沟学院 Java
Zzzzoooo:更新:今天下午有hr联系我去不去客户端,拒了
点赞 评论 收藏
分享
把球:这个听过,你加了就会发现是字节的hr
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务