Strongly connected component (Tarjans's Algo)
Given an unweighted directed graph, your task is to print the members of the strongly connected component in the graph where each component is separated by ', ' (see the example for more clarity). The Graph can have loops.
#include <bits/stdc++.h>
using namespace std;
int t1;
stack<int> s;
void strongcmpt(vector<int> v[],vector<int> &vis,int i,int n,vector<int> &low,
vector<int> &disc,vector<int> &instack)
{
low[i]=disc[i]=++t1,instack[i]=1,s.push(i);
vis[i]=1;
if(i==n)return;
for(int j=0;j<v[i].size();++j)
{
if(vis[v[i][j]]==0)
{
strongcmpt(v,vis,v[i][j],n,low,disc,instack);
}
if(instack[v[i][j]])
low[i]=min(low[i],low[v[i][j]]);
}
if(low[i]==disc[i])
{
while(s.top()!=i)
{
cout<<s.top()<<" ";
instack[s.top()]=0;
s.pop();
}
cout<<s.top()<<",";
instack[s.top()]=0;
s.pop();
}
}
int main() {
//code
int t;
cin>>t;
while(t--)
{
int n,m,x,y;
cin>>n>>m;
vector<int> v[n];
for(int i=0;i<m;++i)
{
cin>>x>>y;
v[x].push_back(y);
}
vector<int> low(n,-1),disc(n,-1),instack(n,0),vis(n,0);
t1=0;
for(int i=0;i<n;++i)
if(vis[i]==0)
strongcmpt(v,vis,i,n,low,disc,instack);
cout<<endl;
}
return 0;
}