xxxxxxxxxx
Assume that you are organizing a global tour with the goal of
seeing every nation. Kosaraju's Algorithm functions similarly
to a clever travel planner. It assists you in locating groupings
of nations where you can move easily between any two without
ever leaving the group. The program effectively investigates
links between nations, much like when you plan your trip,
which facilitates navigating the intricate web of international
travel routes.
xxxxxxxxxx
// 1. Topological sort of original graph G
// 2. Itearte over all the vertices on reverse graph RG, and perform dfs
on reverse graph
// 3. Mark all the current visited node as one component
Note: its like onion-peeling algorithm and removal of sink nodes in
Condensed connected graph
// =======================================================
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1;
vector<int> gr[N], grr[N];
int vis[N];
int color[N];
vector<int> order;
void dfs1(int src) {
vis[src] = 1;
for (auto nbr : gr[src]) {
if (!vis[nbr]) {
dfs1(nbr);
}
}
// i am at this point, bcz i have pushed all subtree
order.push_back(src);
}
void dfs2(int src, int comp) {
vis[src] = 1;
color[src] = comp;
for (auto nbr : grr[src]) {
if (!vis[nbr]) {
dfs2(nbr, comp);
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
gr[x].push_back(y);
grr[y].push_back(x);
}
for (int i = 1; i <= n; i++) {
if(!vis[i]){
dfs1(i);
}
}
reverse(order.begin(), order.end());
memset(vis, 0, sizeof(vis));
int comp = 1;
for (auto x : order) {
if (!vis[x]) {
dfs2(x, comp++);
}
}
cout << "Total SCC are " << comp - 1 << endl;
for(int i=1;i<=n;i++){
cout<<i<<"-->"<<color[i]<<endl;
}
return 0;
}