题目描述
A 国派出将军 uim,对 B 国进行战略性措施,以解救涂炭的生灵。
B 国有 n n n 个城市,这些城市以铁路相连。任意两个城市都可以通过铁路直接或者间接到达。
uim 发现有些铁路被毁坏之后,某两个城市无法互相通过铁路到达。这样的铁路就被称为 key road。
uim 为了尽快使该国的物流系统瘫痪,希望炸毁铁路,以达到存在某两个城市无法互相通过铁路到达的效果。
然而,只有一发炮弹(A 国国会不给钱了)。所以,他能轰炸哪一条铁路呢?
输入格式
第一行 n , m ( 1 ≤ n ≤ 150 n,m\ (1 \leq n\leq 150 n,m (1≤n≤150, 1 ≤ m ≤ 5000 ) 1 \leq m \leq 5000) 1≤m≤5000),分别表示有 n n n 个城市,总共 m m m 条铁路。
以下 m m m 行,每行两个整数 a , b a, b a,b,表示城市 a a a 和城市 b b b 之间有铁路直接连接。
输出格式
输出有若干行。
每行包含两个数字 a , b a,b a,b,其中 a < b a<b a<b,表示 ⟨ a , b ⟩ \lang a,b\rang ⟨a,b⟩ 是 key road。
请注意:输出时,所有的数对 ⟨ a , b ⟩ \lang a,b\rang ⟨a,b⟩ 必须按照 a a a 从小到大排序输出;如果 a a a 相同,则根据 b b b 从小到大排序。
样例 #1
样例输入 #1
6 6
1 2
2 3
2 4
3 5
4 5
5 6
样例输出 #1
1 2
5 6
思路
其实题目的意思就是,在炸掉某条铁路之后,如果整个图不连通了,那么该条铁路就是“key road”。
具体思路如下:
我们来循环枚举每条铁路,然后每次把除了这条铁路外的其他铁路的点都用并查集存储起来。这个时候再用并查集来判断根节点为自己的结点有多少个。
如果根结点等于自己数量大于等于2(即至少存在两个连通分量),就说明如果不将这条铁路连起来,就会有结点之间不能通行。
思路参考:大佬的题解
看有几个连通分量也可以使用BFS。
代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#define endl '\n'
using namespace std;
typedef pair<int, int> PII;// 由于最后输出的排序要求,因此使用pair存储所有铁路
const int N = 160, M = 5010;
int n, m;
vector<PII> road, key_road;// 全部铁路,关键铁路
int p[N];
int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
// 这里输出有个坑,最后输出的所有key road都要满足a < b,因此这里在存储的时候就处理一下
if (a > b) {
swap(a, b);
}
road.push_back({ a,b });
}
// 下面的思路见博客分析
for (int i = 0; i < m; i++) {
for (int j = 1; j <= n; j++) {
p[j] = j;
}
for (int j = 0; j < m; j++) {
if (j == i) {
continue;
}
int a = road[j].first;
int b = road[j].second;
p[find(a)] = find(b);
}
int res = 0;
for (int j = 1; j <= n; j++) {
if (p[j] == j) {
res++;
}
}
if (res > 1) {
key_road.push_back(road[i]);
}
}
// pair默认按先first升序,再按second升序
sort(key_road.begin(), key_road.end());
for (auto r : key_road) {
cout << r.first << " " << r.second << endl;
}
return 0;
}