Strongly connected components

A directed graph G=(V,A)G = (V, A) consists of a set of vertices VV and a set of arcs AA. An arc is an ordered pair (u,v)(u, v), where u,vVu, v \in V. A path from a vertex vi1v_{i_1} to a vertex vikv_{i_k} is a sequence of arcs (vi1,v12),(vi2,vi3),,(vik1,vik)(v_{i_1}, v_{1_2}), (v_{i_2}, v_{i_3}), \dots, (v_{i_{k-1}}, v_{i_k}). By definition, there is always a path from every vertex to itself.

Consider the following equivalence relation: two vertices uu and vv of GG are related if, and only if, there is a path from uu to vv and a path from vv to uu. Every equivalence class resulting from this definition is called a strongly connected component of GG.

Given a directed graph, calculate how many strongly connected components it has.

Input

Input begins with the number of cases. Each case consists of the number of vertices nn and the number of arcs mm, followed by mm pairs (u,v)(u, v). Vertices are numbered starting at 0. There are not repeated arcs, nor self-arcs (v,v)(v, v). Assume 1n1041 \le n \le 10^4.

Output

For every graph, print its number of strongly connected components.

Problem information

Author: Xavier Martínez

Generation: 2026-01-25T11:53:46.637Z

© Jutge.org, 2006–2026.
https://jutge.org