-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathtarjan_graph_algo.cpp
76 lines (61 loc) · 1.11 KB
/
tarjan_graph_algo.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
#include<bits/stdc++.h>
#define fo(i,n) for (int i = 1; i <= n; i++)
#define mod 1000000007
#define pb push_back
#define ff first
#define ss second
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define lli long long int
#define endl '\n'
using namespace std;
vi g[1001];
bool vis[1001] , onStack[1001];
int in[1001] , low[1001];
stack<int> st;
int timer = 1 , SCC = 0;
void dfs(int node)
{
vis[node] = 1;
in[node] = low[node] = timer++;
onStack[node] = true;
st.push(node);
for(int u : g[node])
{
if((vis[u] == true) && (onStack[u] == true))
{
low[node] = min(low[node] , in[u]);
}
else
if(vis[u] == false)
{
dfs(u);
if(onStack[u] == true)
low[node] = min(low[node] , low[u]);
}
}
if(in[node] == low[node])
{
SCC++;
cout<<"SCC #"<<SCC<<endl;
int u;
while(1)
{
u = st.top();
st.pop() , onStack[u] = false;
cout<<u<<" ";
if(u == node) break;
}
cout<<endl;
}
}
int main()
{
int n , m, a , b;
cin>>n>>m;
fo(i , m) cin>>a>>b , g[a].pb(b);
fo(i , n) vis[i] = onStack[i] = false;
fo(i , n)
if(vis[i] == false) dfs(i);
}