题解 | #畅通工程#

畅通工程

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

思路:并查集合并城镇,之后用set判断连通块数量

注意输入格式 while(cin>>n)输入,不然会不通过

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<vector>
#include<unordered_set>
using namespace std;

const int N = 1010;
int p[N];

void init() {
    for (int i = 0; i < N; i++) p[i] = i;
}

int find(int u) {
    if (p[u] != u) p[u] = find(p[u]);
    return p[u];
}

void un(int u, int v) {
    int root1 = find(u), root2 = find(v);
    if (root1 != root2) {
        p[root1] = root2;
    }
}

int main() {

    int n, m;

    while (cin >> n) {
        init();
        if (n == 0) break;
        cin >> m;
        for (int i = 0; i < m; i++) {
            int a, b;
            cin >> a >> b;
            if (find(a) != find(b)) un(a, b);
        }

        unordered_set<int> st;
        for (int i = 1; i <= n; i++) {
            st.insert(find(i));
        }

        cout << st.size() - 1 << endl;
    }

    return 0;
}

王道考研机试 文章被收录于专栏

包含考研机试打卡表题目

全部评论

相关推荐

08-29 17:17
已编辑
门头沟学院
嗨害嗨我来了:张总:你们这些年轻人,这不是把我的爱好暴露了吗?
工作时那些社死瞬间
点赞 评论 收藏
分享
09-21 21:14
门头沟学院
否极泰来来来来:和他说:这里不好骂你,我们加个微信聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务