forked from MohmedIkram/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TarzanAlgo.cpp
70 lines (61 loc) · 1.37 KB
/
TarzanAlgo.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
#include<bits/stdc++.h>
using namespace std;
void dfs(vector<int> adj[],vector<int>& low,vector<int>& disc, vector<int>& instack, stack<int>& s, vector<vector<int>>& ans, int u)
{
static int t=0;
static int count=0;
disc[u]=t;
low[u]=t;
t++;
instack[u]=1;
s.push(u);
for(int v:adj[u])
{
if(disc[v]==-1)
{
dfs(adj,low,disc,instack,s,ans,v);
low[u] = min(low[u],low[v]);
}
else if(instack[v])
low[u] = min(low[u],disc[v]);
}
if(low[u]==disc[u])
{
ans.resize(count+1);
cout<<count<<endl;
while(s.top()!=u)
{
instack[s.top()]=0;
cout<<s.top();
s.pop();
}
cout<<s.top()<<endl;
instack[s.top()]=0;
s.pop();
count++;
}
}
void tarjans(int V, vector<int> adj[])
{
vector<vector<int>> ans;
vector<int> low(V,-1),disc(V,-1),instack(V,0);
stack<int> s;
for(int i=0; i<V; i++)
{
if(disc[i]==-1)
dfs(adj,low,disc,instack,s,ans,i);
}
}
int main()
{
int V,E;
cin>>V>>E;
vector<int> adj[V];
for(int i=0; i<E; i++)
{
int u,v;
cin>>u>>v;
adj[u].push_back(v);
}
tarjans(V,adj);
}