Skip to content

Instantly share code, notes, and snippets.

@Mjkim-Programming
Last active December 21, 2025 02:39
Show Gist options
  • Select an option

  • Save Mjkim-Programming/9eb37c07e38551bbff39d11d02abdeaa to your computer and use it in GitHub Desktop.

Select an option

Save Mjkim-Programming/9eb37c07e38551bbff39d11d02abdeaa to your computer and use it in GitHub Desktop.
SCC template using tarjan
#include <bits/stdc++.h>
#define ll long long
#define FASTIO \
cin.tie(NULL); \
ios::sync_with_stdio(false);
#define END return 0;
#define out cout <<
#define in cin >>
using namespace std;
struct DirectedGraph {
int n;
vector<vector<int>> adj;
vector<int> dfn, low, scc_id;
vector<bool> in_stk;
stack<int> stk;
int dfs_cnt = 0, scc_cnt = 0;
vector<vector<int>> sccs;
DirectedGraph(int n) : n(n), adj(n+1), dfn(n+1), low(n+1), scc_id(n+1), in_stk(n+1) {}
void add_edge(int u, int v) { adj[u].push_back(v); }
void tarjan(int u) {
dfn[u] = low[u] = ++dfs_cnt;
stk.push(u);
in_stk[u] = true;
for (int v : adj[u]) {
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (in_stk[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if (dfn[u] == low[u]) {
vector<int> temp;
while (true) {
int v = stk.top();
stk.pop();
in_stk[v] = false;
scc_id[v] = scc_cnt;
temp.push_back(v);
if (v == u) break;
}
sort(temp.begin(), temp.end());
sccs.push_back(temp);
scc_cnt++;
}
}
void build_scc() {
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
}
};
int main() {
FASTIO
int V, E;in V>>E;
DirectedGraph g(V);
while(E--) {
int A, B;
in A>>B;
g.add_edge(A, B);
}
g.build_scc();
sort(g.sccs.begin(), g.sccs.end(),[](const vector<int>& a, const vector<int>& b) { return a[0] < b[0]; });
out g.sccs.size()<<"\n";
for (vector<int>& temp : g.sccs) {
for (int v : temp) out v<<" ";
out -1<<"\n";
}
END
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment