洛谷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;
}
posted @ 2020-02-21 09:50  quanjun  阅读(123)  评论(0编辑  收藏  举报