-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphIntro18.cpp
More file actions
73 lines (62 loc) · 1.46 KB
/
GraphIntro18.cpp
File metadata and controls
73 lines (62 loc) · 1.46 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
// Tarjans Strongly Connected Component Algorithms
#include<bits/stdc++.h>
using namespace std;
#define V 7
#define pb push_back
unordered_map<int, vector<int>> adj;
void DFS(int u, vector<int>& disc, vector<int>& low, stack<int>& mystack, vector<bool>& presentInStack)
{
static int time = 0;
disc[u] = low[u] = time;
time += 1;
mystack.push(u);
presentInStack[u] = true;
for (int v : adj[u])
{
if (disc[v] == -1) //If v is not visited
{
DFS(v, disc, low, mystack, presentInStack);
low[u] = min(low[u], low[v]);
}
//Differentiate back-edge and cross-edge
else if (presentInStack[v]) //Back-edge case
low[u] = min(low[u], disc[v]);
}
if (low[u] == disc[u]) //If u is head node of SCC
{
cout << "SCC is: ";
while (mystack.top() != u)
{
cout << mystack.top() << " ";
presentInStack[mystack.top()] = false;
mystack.pop();
}
cout << mystack.top() << "\n";
presentInStack[mystack.top()] = false;
mystack.pop();
}
}
void findSCCs_Tarjan()
{
vector<int> disc(V, -1), low(V, -1);
vector<bool> presentInStack(V, false); //Avoids cross-edge
stack<int> mystack;
for (int i = 0; i < V; ++i)
if (disc[i] == -1)
DFS(i, disc, low, mystack, presentInStack);
}
int main()
{
adj[0].pb(1);
adj[1].pb(2);
adj[1].pb(3);
adj[3].pb(4);
adj[4].pb(0);
adj[4].pb(5);
adj[4].pb(6);
adj[5].pb(6);
adj[6].pb(5);
findSCCs_Tarjan();
return 0;
}
//TIME COMPLEXITY: O(V+E)