-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSCC.cpp
More file actions
74 lines (73 loc) · 1.71 KB
/
SCC.cpp
File metadata and controls
74 lines (73 loc) · 1.71 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
#include <bits/stdc++.h>
using namespace std;
#define fr first
#define sc second
#define sz(c) int(c.size())
#define all(c) c.begin(), c.end()
#define rall(c) c.rbegin(), c.rend()
#define vlong long long
vector<vector<int> > SCCs /* The components itself*/;
#define comps SCCs
vector<int> compIndex /* for each node, what is the index of the component this node inside*/
, ind, lowLink;
stack<int> st;
vector<bool> inst;
vector<vector<int> > adj /*The intial graph*/;
int idx = 0;
void init(int n) {
adj.resize(n);
idx = 0;
for (int i = 0; i < n; ++i) {
adj[i].clear();
}
}
void tarjanSCC(int i) {
lowLink[i] = ind[i] = idx++;
st.push(i);
inst[i] = true;
for (int j = 0; j < sz(adj[i]); j++) {
int k = adj[i][j];
if (ind[k] == -1) {
tarjanSCC(k);
lowLink[i] = min(lowLink[i], lowLink[k]);
} else if (inst[k]) {
lowLink[i] = min(lowLink[i], lowLink[k]);
}
}
if (lowLink[i] == ind[i]) {
vector<int> comp;
int n = -1;
while (n != i) {
n = st.top();
st.pop();
comp.push_back(n);
inst[n] = 0;
compIndex[n] = sz(comps);
}
comps.push_back(comp);
}
}
void SCC() {
comps.clear();
compIndex.resize(sz(adj));
ind.clear();
ind.resize(sz(adj), -1);
lowLink.resize(sz(adj));
inst.resize(sz(adj));
idx = 0; //must be intialized by zero;
for (int i = 0; i < sz(adj); i++)
if (ind[i] == -1)
tarjanSCC(i);
}
vector<vector<int> > cmpAdj /*The new graph between components*/;
void computeNewGraph() {
cmpAdj.resize(sz(comps));
for (int i = 0; i < sz(adj); i++) {
for (int j = 0; j < sz(adj[i]); j++) {
int k = adj[i][j];
if (compIndex[k] != compIndex[i]) {
cmpAdj[compIndex[i]].push_back(compIndex[k]);
}
}
}
}