• 洛谷P1656 炸铁路 题解 并查集


    题目链接:https://www.luogu.com.cn/problem/P1656

    解题思路:
    枚举每一条边,假设这条边被删掉,然后用并查集判断剩下的 (m-1) 条边能否让这个图连通。

    实现代码如下:

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 155, maxm = 5050;
    int n, m, f[maxn];
    pair<int, int> edge[maxm];
    vector<pair<int, int> > res;
    void init() {
        for (int i = 1; i <= n; i ++)
            f[i] = i;
    }
    int Find(int x) {
        if (x == f[x]) return x;
        return f[x] = Find(f[x]);
    }
    void Union(int x, int y) {
        int a = Find(x), b = Find(y);
        f[a] = f[b] = f[x] = f[y] = min(a, b);
    }
    bool check(int eid) {
        init();
        for (int i = 0; i < m; i ++) {
            if (i == eid) continue;
            Union(edge[i].first, edge[i].second);
        }
        for (int i = 2; i <= n; i ++) if (Find(1) != Find(i)) return true;
        return false;
    }
    int main() {
        cin >> n >> m;
        for (int i = 0; i < m; i ++) {
            cin >> edge[i].first >> edge[i].second;
            if (edge[i].first > edge[i].second) swap(edge[i].first, edge[i].second);
        }
        for (int i = 0; i < m; i ++) if (check(i)) res.push_back(edge[i]);
        sort(res.begin(), res.end());
        for (vector<pair<int, int> >::iterator it = res.begin(); it != res.end(); it ++) {
            cout << (*it).first << " " << (*it).second << endl;
        }
        return 0;
    }
    
  • 相关阅读:
    第二次结对编程作业
    第5组 团队展示
    第一次结对编程作业
    第一次个人编程作业
    51 Nod 1024 Set
    51 Nod 1007 dp
    YY的GCD 数学
    选课 树形背包dp
    运输问题 费用流
    分配问题 费用流
  • 原文地址:https://www.cnblogs.com/quanjun/p/12340300.html
Copyright © 2020-2023  润新知