-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirected_graph.cpp
More file actions
104 lines (83 loc) · 1.87 KB
/
Copy pathdirected_graph.cpp
File metadata and controls
104 lines (83 loc) · 1.87 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include<bits/stdc++.h>
using namespace std;
struct diGraph {
int n, m, is_cyclic;
vector <int> v, w, topological_sort;
vector <vector <int>> adj, rev;
diGraph() {}
diGraph(int n) : n(n), m(0), is_cyclic(-1) {
adj.resize(n + 1, vector <int>());
rev.resize(n + 1, vector <int>());
}
void add_edge(int ui, int vi, int wi = 0) {
v.push_back(vi);
w.push_back(wi);
adj[ui].push_back(m++);
v.push_back(ui);
w.push_back(wi);
rev[vi].push_back(m++);
}
bool check_cyclic() {
is_cyclic = 0;
vector <int> d(n + 1, 0);
queue <int> q;
for (int i = 1; i <= n; i++) {
for (auto it : adj[i]) d[v[it]]++;
}
for (int i = 1; i <= n; i++) if (!d[i]) q.push(i);
while (q.size()) {
int x = q.front();
q.pop();
topological_sort.push_back(x);
for (auto i : adj[x]) {
d[v[i]]--;
if (d[v[i]] == 0) q.push(v[i]);
}
}
if (topological_sort.size() != n) {
is_cyclic = 1;
topological_sort.clear();
}
return is_cyclic;
}
void scc_helper1(int x, vector <int> &vis, vector <int> &order) {
vis[x] = 1;
for (auto i : adj[x]) {
if (vis[v[i]]) continue;
scc_helper1(v[i], vis, order);
}
order.push_back(x);
}
void scc_helper2(int x, vector <int> &vis, vector <int> &component) {
vis[x] = 1;
component.push_back(x);
for (auto i : rev[x]) {
if (vis[v[i]]) continue;
scc_helper2(v[i], vis, component);
}
}
vector <vector <int>> scc() {
vector <int> order, component;
vector <int> vis(n + 1, 0);
vector <vector <int>> components;
for (int i = 1; i <= n; i++) {
if (!vis[i]) scc_helper1(i, vis, order);
}
vis.assign(n + 1, 0);
reverse(order.begin(), order.end());
for (auto i : order) {
if (!vis[i]) {
component.clear();
scc_helper2(i, vis, component);
components.push_back(component);
}
}
return components;
}
};
int main() {
int n;
cin >> n;
// no of nodes
diGraph g(n);
}