-
Notifications
You must be signed in to change notification settings - Fork 1
/
Finding Bridge
54 lines (42 loc) · 1.04 KB
/
Finding Bridge
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
#include <iostream>
#include <vector>
using namespace std;
const int MAX_N = 300005;
int bridgec;
vector<int> adj [MAX_N];
int lvl [MAX_N];
int dp [MAX_N];
void visit (int vertex) {
dp[vertex] = 0;
for (int nxt : adj[vertex]) {
if (lvl[nxt] == 0) { /* edge to child */
lvl[nxt] = lvl[vertex] + 1;
visit(nxt);
dp[vertex] += dp[nxt];
} else if (lvl[nxt] < lvl[vertex]) { /* edge upwards */
dp[vertex]++;
} else if (lvl[nxt] > lvl[vertex]) { /* edge downwards */
dp[vertex]--;
}
}
/* the parent edge isn't a back-edge, subtract 1 to compensate */
dp[vertex]--;
if (lvl[vertex] > 1 && dp[vertex] == 0) {
bridgec++;
}
}
int main () {
/* problem statement: given a connected graph. calculate the number of bridges. */
ios::sync_with_stdio(false);
int vertexc, edgec;
cin >> vertexc >> edgec;
for (int i = 0; i < edgec; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
lvl[1] = 1;
visit(1);
cout << bridgec << endl;
}