forked from akhiluanandh/utility-functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tarjan_scc.cpp
55 lines (49 loc) · 998 Bytes
/
tarjan_scc.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
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
#define MAX 100000
#define traverse(container, it) \
for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)
int index, dfsnum[MAX], lowlink[MAX];
bool instack[MAX];
vector<int> adj[MAX];
stack<int> S;
void strongconnect(int v)
{
dfsnum[v] = index;
lowlink[v] = index++;
instack[v] = true;
S.push(v);
traverse(adj[v], w)
{
if(dfsnum[*w] == -1)
{
strongconnect(*w);
lowlink[v] = min(lowlink[v], lowlink[*w]);
}
else if(instack[*w])
lowlink[v] = min(lowlink[v], dfsnum[*w]);
}
if(lowlink[v] == dfsnum[v])
{
int w;
do
{
w = S.top();
S.pop();
instack[w] = false;
lowlink[w] = lowlink[v];
} while(w != v && !S.empty());
}
}
int main()
{
index = 0;
for(int i = 0; i < MAX; i++)
dfsnum[i] = -1;
for(int i = 0; i < MAX; i++)
if(dfsnum[i] == -1)
strongconnect(i);
return 0;
}