Skip to content

Commit 115e2b2

Browse files
committed
fix bug in bridge searching offline algorithm in case of duplicate edges
1 parent 101dea5 commit 115e2b2

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

src/graph/bridge-searching.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,10 @@ The implementation needs to distinguish three cases: when we go down the edge in
4040

4141
To implement this, we need a depth first search function which accepts the parent vertex of the current node.
4242

43-
```cpp
43+
For the cases of multiple edges, we need to be careful when ignoring the edge from the parent. To solve this issue, we can add a flag `parent_skipped` which will ensure we only skip the parent once.
44+
45+
```{.cpp file=bridge_searching_offline}
46+
void IS_BRIDGE(int v,int to); // some function to process the found bridge
4447
int n; // number of nodes
4548
vector<vector<int>> adj; // adjacency list of graph
4649

@@ -51,8 +54,12 @@ int timer;
5154
void dfs(int v, int p = -1) {
5255
visited[v] = true;
5356
tin[v] = low[v] = timer++;
57+
bool parent_skipped = false;
5458
for (int to : adj[v]) {
55-
if (to == p) continue;
59+
if (to == p && !parent_skipped) {
60+
parent_skipped = true;
61+
continue;
62+
}
5663
if (visited[to]) {
5764
low[v] = min(low[v], tin[to]);
5865
} else {
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <cassert>
2+
#include <vector>
3+
#include <set>
4+
using namespace std;
5+
6+
#include "bridge_searching_offline.h"
7+
8+
vector<pair<int,int>> bridges;
9+
void IS_BRIDGE(int v,int to){
10+
bridges.push_back({v, to});
11+
}
12+
13+
void normalize(vector<pair<int,int>> &v){
14+
for(auto &p : v){
15+
if(p.first > p.second)swap(p.first, p.second);
16+
}
17+
sort(v.begin(), v.end());
18+
}
19+
20+
void test_suite(
21+
int _n,
22+
vector<vector<int>> _adj,
23+
vector<pair<int,int> > expected_bridges){
24+
bridges.clear();
25+
n = _n;
26+
adj = _adj;
27+
find_bridges();
28+
normalize(&expected_bridges);
29+
normalize(&bridges);
30+
assert(bridges == expected_bridges);
31+
}
32+
33+
int main() {
34+
{
35+
int n = 5;
36+
vector<vector<int>> adj(n);
37+
adj[0].push_back(1), adj[1].push_back(0);
38+
adj[0].push_back(1), adj[1].push_back(0);
39+
40+
adj[2].push_back(3), adj[3].push_back(2);
41+
adj[3].push_back(4), adj[4].push_back(3);
42+
vector<pair<int,int> > expected_bridges;
43+
expected_bridges.push_back({2,3});
44+
expected_bridges.push_back({3,4});
45+
// note that 0-1 is not a bridge due to duplicate edges!
46+
test_suite(n, adj, expected_bridges);
47+
}
48+
}

0 commit comments

Comments
 (0)