-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathSCC_kosaraju.cpp
More file actions
83 lines (78 loc) · 1.6 KB
/
SCC_kosaraju.cpp
File metadata and controls
83 lines (78 loc) · 1.6 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
74
75
76
77
78
79
80
81
82
83
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/* Function to find the number of strongly connected components
* using Kosaraju's algorithm
* V: number of vertices
* adj[]: array of vectors to represent graph
*/
void dfs1(vector<int> adj[],stack<int>& st,int s,bool* vis){
vis[s]=true;
for(auto j:adj[s]){
if(!vis[j]){
dfs1(adj,st,j,vis);
}
}
st.push(s);
}
void dfs2(vector<int> adj[],int s,bool* vis){
vis[s]=true;
for(auto j:adj[s]){
if(!vis[j]){
dfs2(adj,j,vis);
}
}
}
int kosaraju(int V, vector<int> adj[]){
// Your code here
bool vis[V];
for(int i=0;i<V;i++) vis[i]=false;
stack<int> st;
for(int i=0;i<V;i++){
if(!vis[i]){
dfs1(adj,st,i,vis);
}
}
vector<int> newg[V];
for(int i=0;i<V;i++){
vector<int> v;
newg[i]=v;
}
for(int i=0;i<V;i++){
for(auto j: adj[i]){
newg[j].push_back(i);
}
}
for(int i=0;i<V;i++) vis[i]=false;
int ans=0;
while(!st.empty()){
int t=st.top();
st.pop();
if(!vis[t]){
ans++;
dfs2(newg,t,vis);
}
}
return ans;
}
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int a,b ;
cin>>a>>b;
int m,n;
vector<int> adj[a+1];
for(int i=0;i<b;i++){
cin>>m>>n;
adj[m].push_back(n);
}
// exit(0);
cout<<kosaraju(a, adj)<<endl;
}
return 0;
} // } Driver Code Ends