I was recently tasked with finding a way to calculate SCCs in a directed graph by a teacher expecting me to reach Tarjan's or Kosaraju's algorithm, but I reached a completely different solution.
It's arguably a bit worse in both simplicity and complexity,
but I decided to write a blog about it anyway since I think I used some cool ideas, and who knows, maybe somebody else can utilize this either to find a useful variant or in some completely unrelated problem.
My teacher named it KS-SCC, hinting at the fact that it's dumb/useless (in Farsi), lmao.
I will provide a hand-written explanation of my algorithm by me, which is intuitive and informal, and I won't prove anything, and a formal proof of the procedure by Claude (based on my explanation). The core idea is built on the following claims.
I'm terribly sorry for leaving the formal proof to artificial intelligence. I tried proving the algo myself, but with respect to the fact that I'm still a student and have zero experience with this, I couldn't write well and kept leaving gaps in my proof, so I left it to Claude.
To find the SCCs, we do the following recursive depth-first traversal:
mark[u]represents the state of $$$u$$$ in DFS- $$$mark[u] = 0$$$: undiscovered
- $$$mark[u] = 1$$$: discovered & unfinished (active)
- $$$mark[u] = 2$$$: finished
cnt[u]represents the number of cycle-closing edges in $$$u$$$'s subtree such that the cycle includes at least one vertex that is an ancestor of $$$u$$$up[u]represents the node with the lowest distance to the root of the DFS (i.e., height) in $$$u$$$'s SCC
SCC_DFS(u):
1. set mark[u] = 1.
2. go through all nodes v, connected by an edge to u:
if mark[v] == 0 (tree edge)
call SCC_DFS(v)
if cnt[v] > 0
merge the components of u & v
add cnt[v] to cnt[u]
else if mark[v] == 1 (back edge)
increment cnt[u]
decrement cnt[v]
else if mark[v] == 2 (cross edge)
if (mark[up[v]] == 1)
cnt[u]++, cnt[up[v]]--
3. set mark[u] = 2
Intuition of why the procedure works:
Claim 1: a set $$$S$$$ of nodes is strongly connected if and only if there exists a directed closed walk that goes through every vertex of $$$S$$$, and an SCC is a maximal strongly connected set.
Claim 2: two nodes $$$u$$$ & $$$v$$$ are in the same SCC if and only if there exists a directed path from $$$v$$$ to $$$u$$$ and a directed path from $$$u$$$ to $$$v$$$.
[As said, I won't be proving anything here.]
In SCC_DFS, after discovering a vertex $$$u$$$ and visiting the list of edges $$$e = (u \to v)$$$ adjacent to $$$u$$$ during DFS, there are three types you encounter:
If $$$e$$$ is a tree edge:
That means that $$$v$$$ is an undiscovered vertex, so we still don't know anything about $$$v$$$'s relation to $$$u$$$, so first call its SCC_DFS.
Claim 3: if node $$$u$$$ is part of a closed walk $$$W$$$ with one of its ancestors $$$a$$$, there exists a closed walk $$$W'$$$ where $$$par[u], u \in W$$$.
So by Claims 1 & 3, if cnt[v] > 0 then we can merge the $$$u$$$ & $$$v$$$ components. Then we update cnt[u] based on cnt[v].
If $$$e$$$ is a back edge:
It closes a cycle: $$$C = [P = {\text{path from } v \text{ to } u \text{ using tree edges}}] + e$$$, so we update the difference array.
If $$$e$$$ is a cross edge:
By Claim 2, we should merge $$$u$$$ and $$$v$$$ if there exists a path from $$$v$$$ to $$$u$$$. Since $$$v$$$'s subtree is finished (i.e., mark[v] = 2), there needs to be a $$$w$$$ such that $$$v$$$ has a directed path to $$$w$$$ and mark[w] == 1.
Claim 4: such $$$w$$$ exists if and only if the lowest height node in $$$v$$$'s current SCC fits $$$w$$$'s criteria.
This needs a bit of explanation. The list of nodes that can satisfy $$$w$$$ are all $$$v$$$'s ancestors, because if they were not, since $$$v$$$ is finished and $$$v$$$ has a directed path to $$$w$$$, this means that $$$w$$$ has to be discovered by $$$v$$$, but this can't be because mark[w] = 1 and mark[v] = 2. By similar reasoning, all $$$w$$$'s are all ancestors of each other, then we know if mark[x] = 1 then mark[all ancestor of x] = 1, so we can look at the earliest ancestor, i.e., the one with minimum height.
By Claim 4, we can check if mark[up[v]] == 1; then we can treat this cross edge like a back edge from $$$u$$$ to up[v], so we update the difference array accordingly.
Updating up[v]:
We can update up[v] in DSU: when merging the two components with roots $$$u$$$ & $$$v$$$ to a merged component with root $$$u$$$, we do:
if h[up[v]] < h[up[u]]
up[u] = up[v]
Note we update up only for the component's root, so when looking for up[u] we should do up[component_root(u)] instead.
Then the SCC for each node $$$u$$$ is: component_root(u).
Why this finds all SCCs (intuitively)
In my explanation it's obvious that every merge happening is needed. Imagine a certain SCC like $$$C$$$, and imagine the first node of $$$C$$$ discovered in the DFS is $$$r$$$. Then since every node of $$$C$$$ is reachable from $$$r$$$, it's like $$$C$$$ is a hanging piece of the DFS tree from $$$r$$$, and each boundary of this piece is increased when reaching a back edge or a cross edge which links that piece and up to $$$r$$$.
Correctness of the cnt/DSU algorithm for strongly connected components
0. Setting, notation and the algorithm
Let $$$G=(V,E)$$$ be a finite directed multigraph (parallel edges and self-loops are allowed). Write $$$x \rightsquigarrow y$$$ if there is a directed walk from $$$x$$$ to $$$y$$$ in $$$G$$$ (every vertex reaches itself). Write $$$x \sim y$$$ if $$$x \rightsquigarrow y$$$ and $$$y \rightsquigarrow x$$$.
The relation $$$\sim$$$ is an equivalence relation (reflexive, symmetric by definition, transitive because walks can be concatenated). Its equivalence classes are the SCCs. This is the definition used in the proof, so nothing from claims 1–4 of the informal explanation is assumed. What those claims say is re-proved below as Lemmas 5, 6 and 7.
The driver and the initialization. All vertices start with $$$\texttt{mark}=0$$$, $$$\texttt{cnt}=0$$$, $$$\texttt{up}[x]=x$$$, and every vertex is its own DSU class. The driver does: for every vertex $$$r$$$ with $$$\texttt{mark}[r]=0$$$, call $$$\texttt{SCC_DFS}(r)$$$.
SCC_DFS(u):
1. mark[u] = 1
2. for each edge (u -> v):
if mark[v] == 0: // tree edge
SCC_DFS(v)
if cnt[v] > 0: Merge(u, v)
cnt[u] += cnt[v]
else if mark[v] == 1: // back edge (incl. self-loop)
cnt[u]++ ; cnt[v]--
else: // mark[v] == 2 : cross/forward edge
if mark[ up[find(v)] ] == 1:
cnt[u]++ ; cnt[ up[find(v)] ]--
3. mark[u] = 2
Merge(a, b):
A = find(a), B = find(b)
union the classes A, B, and store at the new representative R the value
up[R] = up[B] if h[up[B]] < h[up[A]], else up[A]
(The informal explanation writes $$$\texttt{up}[v]$$$ for $$$\texttt{up}[\texttt{find}(v)]$$$. Below I write $$$U(x)=\texttt{up}[\texttt{find}(x)]$$$.)
Notation about the DFS forest. The tree edges form a rooted forest $$$T$$$.
- $$$p(x)$$$ is the parent of $$$x$$$ in $$$T$$$.
- $$$h(x)$$$ is the depth of $$$x$$$ in its tree (this is the "height" of the explanation).
- $$$\operatorname{sub}(x)$$$ is the set of descendants of $$$x$$$, including $$$x$$$ itself.
- "Ancestor-or-equal" of $$$x$$$ means a vertex on the tree path from the root to $$$x$$$, including $$$x$$$.
- The activation interval of $$$c$$$ is the stretch of execution from step 1 to the end of step 3 of the call $$$\texttt{SCC_DFS}(c)$$$. A vertex is active during its activation interval, which is exactly when $$$\texttt{mark}=1$$$.
Records. Every time the algorithm executes a pair "$$$\texttt{cnt}[a]\text{++}$$$ and $$$\texttt{cnt}[b]\text{--}$$$" it makes a record $$$(a,b)$$$. In the back-edge case the record is $$$(u,v)$$$. In the cross-edge case it is $$$(u,U(v))$$$. Let $$$\mathcal R$$$ be the set of records made over the whole run.
The merged edges. Let $$$M$$$ be the set of tree edges $$$(p(v),v)$$$ for which $$$\texttt{Merge}(p(v),v)$$$ has been called. Because $$$\texttt{Merge}$$$ is only ever called on the endpoints of a tree edge, the DSU classes at any moment are exactly the connected components of the graph $$$(V,M)$$$. Write $$$K(x)$$$ for the class of $$$x$$$.
1. Basic facts about the recursion
Lemma 1 (recursion structure).
- At any moment the active vertices are exactly the vertices on the call stack. They form the tree path from a DFS root to the vertex $$$x$$$ that is currently executing. In particular, when $$$x$$$ is executing, every ancestor-or-equal of $$$x$$$ is active.
- A vertex $$$w$$$ lies in $$$\operatorname{sub}(c)$$$ if and only if $$$w$$$ is discovered during the activation interval of $$$c$$$. Moreover, a vertex of $$$\operatorname{sub}(c)$$$ executes only during that interval.
- When the edge $$$(u\to v)$$$ is examined and $$$\texttt{mark}[v]=0$$$, then $$$v$$$ becomes a child of $$$u$$$. If $$$\texttt{mark}[v]=1$$$, then $$$v$$$ is an ancestor-or-equal of $$$u$$$.
- When $$$\texttt{SCC_DFS}(v)$$$ returns to $$$p(v)$$$, the test "$$$\texttt{cnt}[v] \gt 0$$$" and the possible $$$\texttt{Merge}$$$ are executed immediately, before any other vertex executes any step.
Part 1 holds because each frame on the stack was called by the frame below it, so each vertex is the parent of the vertex above it, and a vertex is active exactly while its frame is on the stack.
For part 2, a call made while $$$c$$$'s frame is on the stack is made by a frame above (or equal to) $$$c$$$'s frame. By induction on the stack height, all such vertices are descendants of $$$c$$$. Conversely, a descendant of $$$c$$$ is called, by definition of $$$T$$$, from its parent's frame, which is above $$$c$$$'s frame or is $$$c$$$'s frame. The same argument shows that a descendant executes only while its frame is on the stack, and this happens inside $$$c$$$'s interval.
Part 3 is by definition of the tree edge (a call is made and $$$u$$$ is its caller), and by part 1 for $$$\texttt{mark}[v]=1$$$.
Part 4 is read off from the pseudocode.
Lemma 2 (shape of records). For every record $$$(a,b)$$$, at the moment it is made, $$$b$$$ is active and is an ancestor-or-equal of $$$a$$$. In particular $$$a\in\operatorname{sub}(b)$$$.
The record is made while $$$a=u$$$ is executing. In the back-edge case $$$b=v$$$ has $$$\texttt{mark}=1$$$, so Lemma 1(3) applies. In the cross-edge case the condition $$$\texttt{mark}[b]=1$$$ is tested, so $$$b$$$ is active, and Lemma 1(1) shows that every active vertex is an ancestor-or-equal of the executing vertex $$$u$$$.
2. What $$$\texttt{cnt}$$$ counts
Lemma 3 (value of cnt). Consider the moment when $$$\texttt{SCC_DFS}(v)$$$ is about to return (just after step 3, before the parent reads $$$\texttt{cnt}[v]$$$). Then
and every such $$$b$$$ is a proper ancestor of $$$v$$$. Thus $$$\texttt{cnt}[v] \gt 0$$$ if and only if some record has its source in $$$\operatorname{sub}(v)$$$ and its target a proper ancestor of $$$v$$$.
Fix a vertex $$$z$$$ and call $$$d(z)=#{\text{records with source } z}-#{\text{records with target } z}$$$, counted over the whole run.
Which events change $$$\texttt{cnt}[z]$$$.
- Records with source $$$z$$$ are made only while $$$z$$$ is executing, hence inside its activation interval.
- Records with target $$$z$$$ are made only while $$$z$$$ is active (Lemma 2), hence inside its activation interval.
- The addition "$$$\texttt{cnt}[z]\mathrel{+}=\texttt{cnt}[\text{child}]$$$" occurs once for each child, inside the activation interval of $$$z$$$.
No other statement touches $$$\texttt{cnt}[z]$$$. Hence at the moment $$$z$$$ is about to return,
Induction on the height of $$$\operatorname{sub}(v)$$$. Suppose that, for every child $$$w$$$ of $$$v$$$, $$$\texttt{cnt}[w]$$$ at its return equals $$$\sum_{z\in\operatorname{sub}(w)}d(z)$$$ (the base case, a leaf, is the displayed formula with no children). Then $$$\texttt{cnt}[v]=\sum_{z\in\operatorname{sub}(v)}d(z)$$$ at the return of $$$v$$$. Here $$$d(z)$$$ is the final value over the whole run. This is legitimate because every record whose source or target lies in $$$\operatorname{sub}(v)$$$ is made inside the activation interval of $$$v$$$ (by the event list above, since all vertices of $$$\operatorname{sub}(v)$$$ are active or executing only inside that interval, Lemma 1(2)). So at the moment $$$v$$$ returns, all of those records have already been made.
Evaluating the sum. With $$$S=\operatorname{sub}(v)$$$,
If $$$b\in S$$$ then $$$a\in\operatorname{sub}(b)\subseteq S$$$ by Lemma 2. Therefore every record counted in the second set is also counted in the first, and the difference is the number of records with $$$a\in S$$$ and $$$b\notin S$$$.
Proper ancestors. For such a record, $$$b$$$ is an ancestor-or-equal of $$$a$$$ (Lemma 2), so $$$b$$$ lies on the tree path from the root to $$$a$$$. That path passes through $$$v$$$ because $$$a\in\operatorname{sub}(v)$$$. Since $$$b\notin\operatorname{sub}(v)$$$, $$$b$$$ lies strictly before $$$v$$$ on this path, i.e., $$$b$$$ is a proper ancestor of $$$v$$$.
3. Structure of the DSU classes and of $$$\texttt{up}$$$
Lemma 4 (classes are tree-connected, and up is the top). At every moment, every class $$$K$$$ has a unique vertex $$$\operatorname{top}(K)\in K$$$ of minimum depth. It is an ancestor-or-equal of every vertex of $$$K$$$ (so $$$K\subseteq\operatorname{sub}(\operatorname{top}K)$$$), and $$$U(x)=\operatorname{top}(K(x))$$$ for every $$$x$$$.
Existence and ancestor property. $$$K$$$ is a connected component of $$$(V,M)$$$ and $$$M\subseteq T$$$. For $$$x,y\in K$$$ there is a path from $$$x$$$ to $$$y$$$ using edges of $$$M$$$. It is a path in the tree $$$T$$$, hence it is the unique tree path from $$$x$$$ to $$$y$$$, and that path contains $$$\operatorname{lca}(x,y)$$$. So $$$\operatorname{lca}(x,y)\in K$$$. Taking the lca of all vertices of $$$K$$$ (repeatedly applying the above to pairs) gives a vertex $$$t\in K$$$ that is an ancestor-or-equal of all vertices of $$$K$$$. It is the unique vertex of minimum depth: any other vertex of $$$K$$$ is a proper descendant of $$$t$$$ and is deeper.
The identity $$$U=\operatorname{top}$$$. Induction over the moments at which classes change. Initially every class is a singleton $$${x}$$$ with $$$\texttt{up}[x]=x$$$. When classes $$$A=K(a)$$$ and $$$B=K(b)$$$ are merged, the union has top $$$t\in A\cup B$$$. Say $$$t\in A$$$. Since $$$t$$$ is an ancestor-or-equal of $$$\operatorname{top}(A)\in A$$$, and $$$\operatorname{top}(A)$$$ is an ancestor-or-equal of $$$t$$$, we get $$$t=\operatorname{top}(A)$$$. The same holds if $$$t\in B$$$. So $$$t\in{\operatorname{top}(A),\operatorname{top}(B)}$$$ and it is the shallower of the two. The two tops have different depths: if they had equal depth, the ancestor-or-equal relation between $$$t$$$ and the other top would force them to be equal, which is impossible for disjoint classes. By the induction hypothesis $$$\texttt{up}[\texttt{find}(a)]=\operatorname{top}(A)$$$ and $$$\texttt{up}[\texttt{find}(b)]=\operatorname{top}(B)$$$, and $$$\texttt{Merge}$$$ stores the shallower of the two (strict comparison $$$h[\text{up}[B]] \lt h[\text{up}[A]]$$$, otherwise the value of $$$A$$$).
Remark (not used later). At the moment $$$\texttt{SCC_DFS}(v)$$$ returns, the only edge of $$$T$$$ between $$$\operatorname{sub}(v)$$$ and the rest of the tree is $$$(p(v),v)$$$, and it is not yet in $$$M$$$. Hence $$$K(v)\subseteq\operatorname{sub}(v)$$$ and $$$\operatorname{top}K(v)=v$$$, which is deeper than $$$\operatorname{top}K(p(v))$$$. So the condition $$$h[\texttt{up}[B]] \lt h[\texttt{up}[A]]$$$ never holds, and $$$\texttt{up}$$$ of the merged class always keeps the value of the parent's class. The update rule is therefore harmless but redundant. The proof does not depend on this.
4. Soundness: classes never contain two different SCCs
Lemma 5 (soundness). At every moment:
- (I1) any two vertices in the same DSU class satisfy $$$x\sim y$$$;
- (I2) every record $$$(a,b)$$$ made so far satisfies $$$a\rightsquigarrow b$$$.
We prove (I1) and (I2) together by induction over the sequence of steps of the algorithm. Initially there are no records and all classes are singletons.
Records. Suppose a record $$$(a,b)$$$ is made, and (I1) holds just before.
- Back-edge case: $$$(a\to b)$$$ is an edge of $$$G$$$, so $$$a\rightsquigarrow b$$$.
- Cross-edge case: $$$b=U(v)$$$ where $$$(a\to v)$$$ is an edge. By Lemma 4, $$$b=\operatorname{top}(K(v))\in K(v)$$$, so by (I1) $$$v\sim b$$$. Hence $$$a\to v\rightsquigarrow b$$$.
Merges. Suppose $$$\texttt{Merge}(u,v)$$$ is executed with $$$u=p(v)$$$, right after $$$\texttt{SCC_DFS}(v)$$$ returned with $$$\texttt{cnt}[v] \gt 0$$$ (Lemma 1(4): nothing else happened in between). By Lemma 3 there is a record $$$(a,b)$$$ with $$$a\in\operatorname{sub}(v)$$$ and $$$b$$$ a proper ancestor of $$$v$$$. We have:
- $$$v\rightsquigarrow a$$$, along the tree path from $$$v$$$ down to $$$a$$$;
- $$$a\rightsquigarrow b$$$ by (I2) for this record;
- $$$b\rightsquigarrow u$$$, along the tree path down from $$$b$$$ to $$$u=p(v)$$$ ($$$b$$$ is an ancestor-or-equal of $$$p(v)$$$);
- $$$u\to v$$$ is a tree edge.
So $$$v\rightsquigarrow u$$$ and $$$u\rightsquigarrow v$$$, i.e., $$$u\sim v$$$. Now take any $$$x\in K(u)$$$ and $$$y\in K(v)$$$. By (I1), $$$x\sim u$$$ and $$$v\sim y$$$, and by transitivity $$$x\sim y$$$. Therefore the merged class again satisfies (I1). Pairs inside $$$K(u)$$$ or inside $$$K(v)$$$ are unaffected.
5. Completeness: every SCC ends up inside a single class
Throughout this section fix an SCC $$$C$$$, and let $$$r$$$ be the vertex of $$$C$$$ that is discovered first (every vertex is discovered exactly once, so "first" is well-defined).
Lemma 6 (an SCC is a connected hanging piece of the tree).
- $$$C\subseteq\operatorname{sub}(r)$$$.
- For every $$$c\in C\setminus{r}$$$, the whole tree path from $$$r$$$ to $$$c$$$ lies in $$$C$$$. In particular $$$p(c)\in C$$$, and $$$r$$$ is a proper ancestor of $$$c$$$.
(1) Let $$$w\in C\setminus{r}$$$ and take a simple path $$$r=z_0\to z_1\to\dots\to z_k=w$$$ in $$$G$$$. Every $$$z_i$$$ satisfies $$$r\rightsquigarrow z_i\rightsquigarrow w\rightsquigarrow r$$$, so $$$z_i\in C$$$. In particular no $$$z_i$$$ is discovered before $$$r$$$. Suppose not all $$$z_i$$$ are in $$$\operatorname{sub}(r)$$$ and let $$$i\ge1$$$ be the smallest index with $$$z_i\notin\operatorname{sub}(r)$$$. Then $$$z_{i-1}\in\operatorname{sub}(r)$$$. When $$$z_{i-1}$$$ examines the edge $$$(z_{i-1}\to z_i)$$$, the vertex $$$r$$$ is active (Lemma 1(1),(2)), and:
- If $$$\texttt{mark}[z_i]=0$$$: $$$z_i$$$ becomes a child of $$$z_{i-1}$$$, hence lies in $$$\operatorname{sub}(r)$$$. Contradiction.
- If $$$\texttt{mark}[z_i]=1$$$: $$$z_i$$$ is an ancestor-or-equal of $$$z_{i-1}$$$, so it lies on the path from the root through $$$r$$$ to $$$z_{i-1}$$$. As $$$z_i\notin\operatorname{sub}(r)$$$, it is a proper ancestor of $$$r$$$ and was discovered before $$$r$$$, although $$$z_i\in C$$$. Contradiction.
- If $$$\texttt{mark}[z_i]=2$$$: $$$z_i$$$ was discovered after $$$r$$$ (it is in $$$C$$$ and $$$z_i\ne r$$$ since the path is simple) and has already finished while $$$r$$$ is still active. So it was discovered during the activation interval of $$$r$$$, and by Lemma 1(2) it lies in $$$\operatorname{sub}(r)$$$. Contradiction.
(2) Let $$$c\in C\setminus{r}$$$. By (1), $$$c\in\operatorname{sub}(r)$$$ and $$$c\neq r$$$, so $$$r$$$ is a proper ancestor of $$$c$$$. Every vertex $$$z$$$ on the tree path from $$$r$$$ to $$$c$$$ satisfies $$$r\rightsquigarrow z\rightsquigarrow c\rightsquigarrow r$$$ (tree edges are edges of $$$G$$$), so $$$z\in C$$$.
Lemma 7 (every non-first vertex of an SCC merges with its parent). For every vertex $$$c\in C\setminus{r}$$$, at the moment $$$\texttt{SCC_DFS}(c)$$$ is about to return we have $$$\texttt{cnt}[c]\ge1$$$. Consequently $$$(p(c),c)\in M$$$ right after the return.
Strong induction on the finishing order of the vertices. Assume the statement holds for all vertices of $$$C\setminus{r}$$$ that finish before $$$c$$$ finishes.
Choosing an exit edge. Since $$$c\rightsquigarrow r$$$, choose a simple path $$$c=z_0\to\dots\to z_k=r$$$ in $$$G$$$. Every $$$z_i$$$ lies in $$$C$$$ (same argument as in Lemma 6(1)). The vertex $$$r$$$ is a proper ancestor of $$$c$$$ by Lemma 6(2), so $$$r\notin\operatorname{sub}(c)$$$. Let $$$i$$$ be the smallest index with $$$z_{i+1}\notin\operatorname{sub}(c)$$$, and set $$$x=z_i\in\operatorname{sub}(c)$$$, $$$y=z_{i+1}\in C\setminus\operatorname{sub}(c)$$$. The edge $$$e=(x\to y)$$$ is examined at some moment $$$\tau$$$ during the execution of $$$x$$$. At $$$\tau$$$, $$$c$$$ is active (Lemma 1(1)), and so is $$$r$$$, being an ancestor of $$$c$$$.
Case $$$\texttt{mark}[y]=0$$$ at $$$\tau$$$. Then $$$y$$$ becomes a child of $$$x$$$, so $$$y\in\operatorname{sub}(x)\subseteq\operatorname{sub}(c)$$$. Impossible.
Case $$$\texttt{mark}[y]=1$$$ at $$$\tau$$$. Then $$$y$$$ is an ancestor-or-equal of $$$x$$$ (Lemma 1(3)), and $$$y\notin\operatorname{sub}(c)$$$. The record $$$(x,y)$$$ is made, with $$$x\in\operatorname{sub}(c)$$$ and $$$y\notin\operatorname{sub}(c)$$$.
Case $$$\texttt{mark}[y]=2$$$ at $$$\tau$$$. Let $$$t=U(y)=\operatorname{top}(K(y))$$$ at moment $$$\tau$$$ (Lemma 4). We claim that $$$\texttt{mark}[t]=1$$$ at $$$\tau$$$.
- Since $$$y\in C$$$ and by (I1) of Lemma 5 all vertices of $$$K(y)$$$ are equivalent to $$$y$$$, we have $$$K(y)\subseteq C$$$ and in particular $$$t\in C$$$.
- $$$t$$$ is an ancestor-or-equal of $$$y$$$ (Lemma 4), so $$$t$$$ has been discovered: $$$\texttt{mark}[t]\in{1,2}$$$.
- Suppose, for contradiction, that $$$\texttt{mark}[t]=2$$$. Since $$$r$$$ is active at $$$\tau$$$, $$$t\ne r$$$, so $$$t\in C\setminus{r}$$$. The vertex $$$t$$$ finished before $$$\tau$$$, hence before $$$c$$$ finishes. By the induction hypothesis, $$$\texttt{cnt}[t]\ge1$$$ when $$$t$$$ returned, so by Lemma 1(4) the edge $$$(p(t),t)$$$ was put in $$$M$$$ immediately, before $$$\tau$$$. Hence $$$p(t)\in K(t)=K(y)$$$ at $$$\tau$$$ (classes only grow). But $$$h(p(t)) \lt h(t)$$$, which contradicts $$$t$$$ being the unique vertex of minimum depth in $$$K(y)$$$.
So $$$\texttt{mark}[t]=1$$$, the test succeeds, and the record $$$(x,t)$$$ is made. It remains to see that $$$t\notin\operatorname{sub}(c)$$$. If $$$t\in\operatorname{sub}(c)$$$, then $$$y\in\operatorname{sub}(t)\subseteq\operatorname{sub}(c)$$$ (Lemma 4: $$$t$$$ is an ancestor-or-equal of $$$y$$$), contradicting $$$y\notin\operatorname{sub}(c)$$$.
Conclusion. In both possible cases a record $$$(x,b)$$$ was made with $$$x\in\operatorname{sub}(c)$$$ and $$$b\notin\operatorname{sub}(c)$$$. Lemma 3 then gives $$$\texttt{cnt}[c]\ge1$$$ when $$$c$$$ returns. Note that $$$c$$$ has a parent, since $$$c\in\operatorname{sub}(r)\setminus{r}$$$. By Lemma 1(4), $$$\texttt{Merge}(p(c),c)$$$ is executed at once, so $$$(p(c),c)\in M$$$.
6. The theorem
Theorem. When the driver terminates, for all $$$x,y\in V$$$: $$$\texttt{find}(x)=\texttt{find}(y)$$$ if and only if $$$x\sim y$$$. So the DSU representative $$$\texttt{find}(x)$$$ identifies the SCC of $$$x$$$.
($$$\Rightarrow$$$) This is (I1) of Lemma 5 applied at the end of the run.
($$$\Leftarrow$$$) Let $$$x\sim y$$$ and let $$$C$$$ be their SCC with first-discovered vertex $$$r$$$. We show that every $$$c\in C$$$ lies in $$$K(r)$$$, by induction on $$$h(c)-h(r)$$$, which is $$$\ge0$$$ by Lemma 6(1). For $$$c=r$$$ this is trivial. If $$$c\ne r$$$, then $$$p(c)\in C$$$ (Lemma 6(2)) and $$$h(p(c))-h(r) \lt h(c)-h(r)$$$, so by the induction hypothesis $$$p(c)\in K(r)$$$. By Lemma 7, $$$(p(c),c)\in M$$$, so $$$c\in K(p(c))=K(r)$$$. Thus $$$C\subseteq K(r)$$$, and in particular $$$x,y\in K(r)$$$, i.e., $$$\texttt{find}(x)=\texttt{find}(y)$$$.
7. Remarks
- Cross edges include forward edges. The branch "$$$\texttt{mark}[v]=2$$$" is also taken when $$$v$$$ is a finished descendant of $$$u$$$. The proof never assumed otherwise. Lemma 5 only needs $$$u\to v\rightsquigarrow U(v)$$$, and Lemma 2 only needs $$$U(v)$$$ to be active. If $$$U(v)=u$$$, the record is $$$(u,u)$$$, which changes nothing, and $$$u\in K(v)$$$ already.
- Self-loops and parallel edges are covered by the back-edge case. A record $$$(u,u)$$$ adds $$$+1-1$$$ to the same counter. Parallel edges are counted with multiplicity, which is harmless since only "$$$\ge1$$$" matters.
- Where each informal claim went. Claims 1–2 are replaced by the definition of SCC as a class of $$$\sim$$$. Claim 3 is Lemma 5 (merge step). Claim 4 is Lemma 7 together with Lemma 4: it shows that checking only the single vertex $$$U(v)$$$, the top of $$$v$$$'s current class, is enough, because if $$$v$$$ can reach any active vertex of its SCC then its class top is active. The "hanging piece" intuition is Lemma 6.
- Complexity (not part of correctness). Each edge causes $$$O(1)$$$ $$$\texttt{find}$$$ operations and each tree edge causes at most one union, so the total is $$$O((|V|+|E|)\,\alpha(|V|))$$$ with union by size/rank and path compression.
The following is my Implementation of the algorithm
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define se second
#define pb push_back
#define Fast ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr)
#define Tests int tt; cin >> tt; while(tt--) input(), solve(), output()
#define Single input(), solve(), output()
// 0 1 2 3 4 5 6 7 8 9 | n = 10
const int N = 1e5 + 5;
vector<int> adj[N];
int n, m, par[N], cnt[N], h[N], up[N], mark[N];
int get_par(int u) {
return par[u] < 0 ? u : par[u] = get_par(par[u]);
}
bool merge(int u, int v) {
if ((u = get_par(u)) == (v = get_par(v)))
return false;
if (par[v] < par[u])
swap(u, v);
up[u] = h[up[u]] < h[up[v]] ? up[u] : up[v];
par[u] += par[v], par[v] = u;
return true;
}
void dfs(int u) {
mark[u] = 1;
for (int v : adj[u])
if (!mark[v]) {
h[v] = h[u] + 1, dfs(v);
if (cnt[v])
merge(u, v);
cnt[u] += cnt[v];
}
else if (mark[up[get_par(v)]] == 1)
cnt[u]++, cnt[up[get_par(v)]]--;
mark[u] = 2;
}
void input() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--, v--;
adj[u].pb(v);
}
}
void solve() {
memset(par, -1, sizeof par);
for (int u = 0; u < n; u++)
if (!mark[u])
dfs(u);
}
void output() {
for (int u = 0; u < n; u++)
cout << get_par(u) << ' ';
cout << '\n';
}
int main() {
Fast;
Single;
}
Note: ive abbreviated and merged the cross-edge and back-edge branch since,
if $$$mark[v] == 1$$$ then by earlier explanation also $$$mark[up[get$$$_$$$par(v)]] == 1$$$.
the rest of the changes is obvious after a bit of thought.
Quick status: all the testing is done, and here are the results.
[b]Result: the code is correct on everything I threw at it.[/b]
[list] [*] [b]Small random graphs:[/b] 5000 tests with n ≤ 9, including self-loops and multi-edges, compared against a Floyd-Warshall brute force (u and v share a component iff each reaches the other). 0 failures. [] [b]Medium random graphs:[/b] 3000 tests with n from 10 to 40 and varied density. 0 failures. [] [b]Large graphs (n = 1e5):[/b] [] A single 1e5-vertex cycle (recursion depth 1e5) ran in about 0.04s with the default 8 MB stack and gave 1 component. [] A random graph with 2e5 edges ran in about 0.07s and gave 36505 SCCs. I checked it against an iterative Tarjan and the partitions match exactly. [/list]
[b]Does it match the described algorithm?[/b] You didn't paste the description, so I can only say what the code does:
[list] [] It runs a DFS and keeps [tt]cnt[u][/tt], the number of non-tree edges that cover the tree edge (parent, u). [] A non-tree edge u→v counts only if the top of v's component ([tt]up[id[v]][/tt]) is still on the stack. The [tt]cnt[top]--[/tt] cancels the edge at that top so it doesn't cover anything above it. [] After a child returns, [tt]cnt[v] > 0[/tt] means the edge (u, v) lies on a cycle, so it merges the two components. [] Merging is small-to-large (DSU with member lists), and [tt]up[/tt] becomes whichever top is shallower. [/list]
If your description is a cover-counting plus small-to-large merge, it matches. If you paste the description, I can compare it point by point.
[b]Things to watch:[/b]
[list] [*] [tt]Tests[/tt] would break this code because [tt]adj[/tt], [tt]mark[/tt], [tt]cnt[/tt] and [tt]h[/tt] are never cleared between cases. This is fine with [tt]Single[/tt]. [] The output is the component representative ([tt]id[u][/tt]), not labels numbered 1..k. Some judges need the numbered form. [] Recursion depth reaches 1e5. It worked on my 8 MB stack, but a judge with a smaller stack could overflow on a chain. [/list]
[b]give a report on the test you throw at it and it response, memory, complexity, and difference with tarjan or kosarujo[/b]
[hr]
[b]Test report: SCC via cover-counting + small-to-large merging[/b]
[b]1. Tests and results[/b]
[table] [tr] [td][b]#[/b][/td] [td][b]Test[/b][/td] [td][b]Size[/b][/td] [td][b]Checker[/b][/td] [td][b]Result[/b][/td] [/tr] [tr] [td]1[/td] [td]Random graphs with self-loops and multi-edges[/td] [td]5000 cases, n ≤ 9[/td] [td]Floyd-Warshall transitive closure[/td] [td]0 failures[/td] [/tr] [tr] [td]2[/td] [td]Random graphs, sparse to dense[/td] [td]3000 cases, n = 10–40, m ≈ 0.5n–3n[/td] [td]Same brute force[/td] [td]0 failures[/td] [/tr] [tr] [td]3[/td] [td]One big cycle (recursion depth 1e5)[/td] [td]n = 1e5, m = 1e5[/td] [td]Expected 1 SCC[/td] [td]1 SCC, ~0.04 s[/td] [/tr] [tr] [td]4[/td] [td]Random sparse graph[/td] [td]n = 1e5, m = 2e5[/td] [td]Independent iterative Tarjan[/td] [td]Partitions identical (36505 SCCs), ~0.06 s[/td] [/tr] [tr] [td]5[/td] [td]Binary tree with leaves pointing back to the root[/td] [td]n = 1e5[/td] [td]Expected 1 SCC[/td] [td]1 SCC, ~0.06 s[/td] [/tr] [tr] [td]6[/td] [td]Bidirectional path (many merges, depth 1e5)[/td] [td]n = 1e5, m ≈ 2e5[/td] [td]Expected 1 SCC[/td] [td]1 SCC, ~0.06 s[/td] [/tr] [/table]
Checks:
[list] [*] [b]Correctness check:[/b] u and v share a component exactly when [tt]id[u] == id[v][/tt]. It is compared as a partition, so the representative labels don't matter. [] [b]Timing:[/b] the times are wall-clock on this sandbox with [tt]-O2[/tt]. [] [b]Not covered:[/b] I did not run an adversarial case built to maximize small-to-large work. The random and structured cases above all ran in under 0.1 s. [/list]
[b]2. Memory[/b]
[list] [*] [b]Peak RSS:[/b] about 24 MB on both the 1e5 cycle and the 1e5 random graph. That includes the I/O buffers and the recursion stack. [] [b]Static arrays:[/b] these are six [tt]int[N][/tt] arrays, which is about 2.4 MB, plus the [tt]cmp[/tt] and [tt]adj[/tt] vectors. Each vector costs at least 24 bytes, so that is about 5 MB for 2×N vectors. [] [b]Edges and members:[/b] [tt]adj[/tt] holds m ints, and the [tt]cmp[/tt] lists hold n ints in total. Small-to-large merging does not duplicate members, because each move happens to the larger list and [tt]clear()[/tt] empties the old one. The vector [tt]capacity[/tt] can stay allocated after [tt]clear()[/tt], so some slack remains. [] [b]Recursion stack:[/b] the DFS stack is O(depth), up to n frames, so up to 1e5 frames in the worst case. This was the biggest part of the 24 MB. [] [b]Overall:[/b] memory is O(n + m). [/list]
[b]3. Complexity[/b]
[list] [*] [b]DFS and cover counting:[/b] O(n + m). Each edge is examined once, and each check [tt]mark[up[id[v]]][/tt] is O(1). [] [b]Merging:[/b] small-to-large moves each vertex only when its component at least doubles in size. That is O(n log n) total. [] [b]Total:[/b] O(n log n + m) time. It is not strictly linear. [/list]



