-
Notifications
You must be signed in to change notification settings - Fork 153
/
bridges_in_graph.cpp
89 lines (74 loc) · 1.84 KB
/
bridges_in_graph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Description : Bridges (Find bridges in a graph)
* Usage: See below O(V)
* Source: https://github.com/dragonslayerx
*/
#include<iostream>
#include<vector>
#include<cstdio>
#include <cstring>
#include<list>
#include<set>
using namespace std;
#define INVALID_NUMBER -1
#define INVALID_EDGE -1
typedef vector<list<pair<int,int> > > graph;
vector<int> bridges;
vector<int> low;
vector<int> dfsNumbers;
graph G;
void calculateBridges(int currentNode, int &time, int parentEdge=INVALID_EDGE) {
if(dfsNumbers[currentNode]==INVALID_NUMBER)
{
dfsNumbers[currentNode]=low[currentNode]=(++time);
for(list<pair<int,int> >::const_iterator i=G[currentNode].begin();i!=G[currentNode].end();i++)
{
int currentEdge=i->second;
if(currentEdge!=parentEdge){
int destination = i->first;
calculateBridges(destination, time, currentEdge);
if(low[destination]>dfsNumbers[currentNode]) {
bridges.push_back(currentEdge);
}
low[currentNode]=min(low[currentNode],low[destination]);
}
}
}
}
bool isVisited[100005];
int dfs(vector<vector<int> > &G, int u){
isVisited[u] = 1;
int members = 1;
for (int i = 0; i < G[u].size(); i++) {
if (!isVisited[G[u][i]]) {
members += dfs(G, G[u][i]);
}
}
return members;
}
int main(){
ios::sync_with_stdio(false);
int n,m;
cin>>n>>m;
low.resize(n);
dfsNumbers.resize(n,INVALID_NUMBER);
vector<pair<int,int> > edges;
vector<vector<int> > Td(n);
G.resize(n);
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
a--, b--;
edges.push_back(make_pair(a, b));
G[a].push_back(make_pair(b,i));
G[b].push_back(make_pair(a,i));
}
bridges.reserve(m);
int initialTime = 0;
for(int i=0;i<n;i++) {
calculateBridges(i, initialTime);
}
for (int i : bridges) {
cout << edges[i].first << " " << edges[i].second << endl;
}
}