Problem:


Score : 100 points

Problem Statement

You are given a directed graph with N vertices and M edges, not necessarily simple. The i-th edge is oriented from the vertex a_i to the vertex b_i.
Divide this graph into strongly connected components and print them in their topological order.

Constraints

1 \leq N \leq 500,000

1 \leq M \leq 500,000

0 \leq a_i, b_i < N

Input

Input is given from Standard Input in the following format:

N M
a_0 b_0
a_1 b_1
:
a_{M - 1} b_{M - 1}

Output

Print 1+K lines, where K is the number of strongly connected components.
Print K on the first line. 
Print the information of each strongly connected component in next K lines in the following format, where l is the number of vertices in the strongly connected component and v_i is the index of the vertex in it.

l v_0 v_1 ... v_{l-1}

Here, for each edge (a_i, b_i), b_i should not appear in earlier line than a_i.

If there are multiple correct output, print any of them.

Sample Input 1

6 7
1 4
5 2
3 0
5 5
4 1
0 3
4 2

Sample Output 1

4
1 5
2 4 1
1 2
2 3 0



Sample input:
6 7
1 4
5 2
3 0
5 5
4 1
0 3
4 2


Sample output:
4
1 5
2 4 1
1 2
2 3 0

Submission status: Accepted

Solution code:
# TODO: メモリリーク確認
# TODO: __repr__ を書く

code_scc_graph = r"""
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

// 元のライブラリの private を剥がした

// >>> AtCoder >>>

#ifndef ATCODER_SCC_HPP
#define ATCODER_SCC_HPP 1

#include <algorithm>

#ifndef ATCODER_INTERNAL_SCC_HPP
#define ATCODER_INTERNAL_SCC_HPP 1

#include <algorithm>
#include <utility>
#include <vector>

namespace atcoder {
namespace internal {

template <class E> struct csr {
    std::vector<int> start;
    std::vector<E> elist;
    csr(int n, const std::vector<std::pair<int, E>>& edges)
        : start(n + 1), elist(edges.size()) {
        for (auto e : edges) {
            start[e.first + 1]++;
        }
        for (int i = 1; i <= n; i++) {
            start[i] += start[i - 1];
        }
        auto counter = start;
        for (auto e : edges) {
            elist[counter[e.first]++] = e.second;
        }
    }
};

// Reference:
// R. Tarjan,
// Depth-First Search and Linear Graph Algorithms
struct scc_graph {
  public:
    scc_graph(int n) : _n(n) {}

    int num_vertices() { return _n; }

    void add_edge(int from, int to) { edges.push_back({from, {to}}); }

    // @return pair of (# of scc, scc id)
    std::pair<int, std::vector<int>> scc_ids() {
        auto g = csr<edge>(_n, edges);
        int now_ord = 0, group_num = 0;
        std::vector<int> visited, low(_n), ord(_n, -1), ids(_n);
        visited.reserve(_n);
        auto dfs = [&](auto self, int v) -> void {
            low[v] = ord[v] = now_ord++;
            visited.push_back(v);
            for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                auto to = g.elist[i].to;
                if (ord[to] == -1) {
                    self(self, to);
                    low[v] = std::min(low[v], low[to]);
                } else {
                    low[v] = std::min(low[v], ord[to]);
                }
            }
            if (low[v] == ord[v]) {
                while (true) {
                    int u = visited.back();
                    visited.pop_back();
                    ord[u] = _n;
                    ids[u] = group_num;
                    if (u == v) break;
                }
                group_num++;
            }
        };
        for (int i = 0; i < _n; i++) {
            if (ord[i] == -1) dfs(dfs, i);
        }
        for (auto& x : ids) {
            x = group_num - 1 - x;
        }
        return {group_num, ids};
    }

    std::vector<std::vector<int>> scc() {
        auto ids = scc_ids();
        int group_num = ids.first;
        std::vector<int> counts(group_num);
        for (auto x : ids.second) counts[x]++;
        std::vector<std::vector<int>> groups(ids.first);
        for (int i = 0; i < group_num; i++) {
            groups[i].reserve(counts[i]);
        }
        for (int i = 0; i < _n; i++) {
            groups[ids.second[i]].push_back(i);
        }
        return groups;
    }

  private:
    int _n;
    struct edge {
        int to;
    };
    std::vector<std::pair<int, edge>> edges;
};

}  // namespace internal

}  // namespace atcoder

#endif  // ATCODER_INTERNAL_SCC_HPP

#include <cassert>
#include <vector>

namespace atcoder {

struct scc_graph {
  public:
    scc_graph() : internal(0) {}
    scc_graph(int n) : internal(n) {}

    void add_edge(int from, int to) {
        int n = internal.num_vertices();
        assert(0 <= from && from < n);
        assert(0 <= to && to < n);
        internal.add_edge(from, to);
    }

    std::vector<std::vector<int>> scc() { return internal.scc(); }

//  private:
    internal::scc_graph internal;
};

}  // namespace atcoder

#endif  // ATCODER_SCC_HPP

// <<< AtCoder <<<

using namespace std;
using namespace atcoder;
#define PARSE_ARGS(types, ...) if(!PyArg_ParseTuple(args, types, __VA_ARGS__)) return NULL


struct SCCGraph{
    PyObject_HEAD
    scc_graph* graph;
    const int n() const { return graph->internal.num_vertices(); }
};


extern PyTypeObject SCCGraphType;


// >>> SCCGraph definition >>>

static void SCCGraph_dealloc(SCCGraph* self){
    delete self->graph;
    Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* SCCGraph_new(PyTypeObject* type, PyObject* args, PyObject* kwds){
    return type->tp_alloc(type, 0);
}
static int SCCGraph_init(SCCGraph* self, PyObject* args){
    long n;
    if(!PyArg_ParseTuple(args, "l", &n)) return -1;
    if(n < 0 || n > (long)1e8){
        PyErr_Format(PyExc_IndexError,
            "SCCGraph constructor constraint error (constraint: 0<=n<=1e8, got n=%d)", n);
        return -1;
    }
    self->graph = new scc_graph(n);
    return 0;
}
static PyObject* SCCGraph_add_edge(SCCGraph* self, PyObject* args){
    long from, to;
    PARSE_ARGS("ll", &from, &to);
    if(from < 0 || from >= self->n() || to < 0 || to >= self->n()){
        PyErr_Format(PyExc_IndexError,
            "SCCGraph add_ede index out of range (n=%d, from=%d, to=%d)", self->n(), from, to);
        return (PyObject*)NULL;
    }
    self->graph->add_edge(from, to);
    Py_RETURN_NONE;
}
static PyObject* SCCGraph_scc(SCCGraph* self, PyObject* args){
    const vector<vector<int>>& scc = self->graph->scc();
    PyObject* list = PyList_New(scc.size());
    for(int i = 0; i < scc.size(); i++){
        PyObject* lst = PyList_New(scc[i].size());
        for(int j = 0; j < scc[i].size(); j++){
            PyList_SET_ITEM(lst, j, Py_BuildValue("l", scc[i][j]));
        }
        PyList_SET_ITEM(list, i, lst);
    }
    return list;
}
/*
static PyObject* SCCGraph_repr(PyObject* self){
    PyObject* res = PyUnicode_FromFormat("SCCGraph()");
    return res;
}
*/
static PyMethodDef SCCGraph_methods[] = {
    {"add_edge", (PyCFunction)SCCGraph_add_edge, METH_VARARGS, "Add clause"},
    {"scc", (PyCFunction)SCCGraph_scc, METH_VARARGS, "Check if problem satisfiable"},
    {NULL}  /* Sentinel */
};
PyTypeObject SCCGraphType = {
    PyObject_HEAD_INIT(NULL)
    "acl_scc.SCCGraph",                 /*tp_name*/
    sizeof(SCCGraph),                   /*tp_basicsize*/
    0,                                  /*tp_itemsize*/
    (destructor)SCCGraph_dealloc,       /*tp_dealloc*/
    0,                                  /*tp_print*/
    0,                                  /*tp_getattr*/
    0,                                  /*tp_setattr*/
    0,                                  /*reserved*/
    0,//SCCGraph_repr,                    /*tp_repr*/
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*tp_call*/
    0,                                  /*tp_str*/
    0,                                  /*tp_getattro*/
    0,                                  /*tp_setattro*/
    0,                                  /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
    0,                                  /*tp_doc*/
    0,                                  /*tp_traverse*/
    0,                                  /*tp_clear*/
    0,                                  /*tp_richcompare*/
    0,                                  /*tp_weaklistoffset*/
    0,                                  /*tp_iter*/
    0,                                  /*tp_iternext*/
    SCCGraph_methods,                   /*tp_methods*/
    0,                                  /*tp_members*/
    0,                                  /*tp_getset*/
    0,                                  /*tp_base*/
    0,                                  /*tp_dict*/
    0,                                  /*tp_descr_get*/
    0,                                  /*tp_descr_set*/
    0,                                  /*tp_dictoffset*/
    (initproc)SCCGraph_init,            /*tp_init*/
    0,                                  /*tp_alloc*/
    SCCGraph_new,                       /*tp_new*/
    0,                                  /*tp_free*/
    0,                                  /*tp_is_gc*/
    0,                                  /*tp_bases*/
    0,                                  /*tp_mro*/
    0,                                  /*tp_cache*/
    0,                                  /*tp_subclasses*/
    0,                                  /*tp_weaklist*/
    0,                                  /*tp_del*/
    0,                                  /*tp_version_tag*/
    0,                                  /*tp_finalize*/
};

// <<< SCCGraph definition <<<


static PyModuleDef acl_sccmodule = {
    PyModuleDef_HEAD_INIT,
    "acl_scc",
    NULL,
    -1,
};

PyMODINIT_FUNC PyInit_acl_scc(void)
{
    PyObject* m;
    if(PyType_Ready(&SCCGraphType) < 0) return NULL;

    m = PyModule_Create(&acl_sccmodule);
    if(m == NULL) return NULL;

    Py_INCREF(&SCCGraphType);
    if (PyModule_AddObject(m, "SCCGraph", (PyObject*)&SCCGraphType) < 0) {
        Py_DECREF(&SCCGraphType);
        Py_DECREF(m);
        return NULL;
    }
    
    return m;
}
"""
code_scc_graph_setup = r"""
from distutils.core import setup, Extension
module = Extension(
    "acl_scc",
    sources=["scc_graph.cpp"],
    extra_compile_args=["-O3", "-march=native", "-std=c++14"]
)
setup(
    name="acl_scc",
    version="0.0.1",
    description="wrapper for atcoder library scc",
    ext_modules=[module]
)
"""

import os
import sys

if sys.argv[-1] == "ONLINE_JUDGE" or os.getcwd() != "/imojudge/sandbox":
    with open("scc_graph.cpp", "w") as f:
        f.write(code_scc_graph)
    with open("scc_graph_setup.py", "w") as f:
        f.write(code_scc_graph_setup)
    os.system(f"{sys.executable} scc_graph_setup.py build_ext --inplace")

from acl_scc import SCCGraph


def main():
    N, M = map(int, sys.stdin.buffer.readline().split())
    m = map(int, sys.stdin.buffer.read().split())
    g = SCCGraph(N)
    for a, b in zip(m, m):
        g.add_edge(a, b)
    scc = g.scc()
    print(len(scc))
    for v in scc:
        print(len(v), " ".join(map(str, v)))

main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)

class SCC:

    def __init__(self, n):
        self.n = n
        self.graph = [[] for i in range(n)]
        self.graph_rev = [[] for i in range(n)]
        self.used = [False]*n

    def add_edge(self, fr, to):
        if fr == to:
            return
        self.graph[fr].append(to)
        self.graph_rev[to].append(fr)

    def dfs(self, node, graph):
        self.used[node] = True
        for nex in graph[node]:
            if self.used[nex]:
                continue
            self.dfs(nex,graph)
        self.order.append(node)

    def first_dfs(self):
        self.used = [False]*self.n
        self.order = []
        for i in range(self.n):
            if self.used[i]:
                continue
            self.dfs(i,self.graph)
    
    def second_dfs(self):
        self.used = [False]*self.n
        self.ans = []
        for node in reversed(self.order):
            if self.used[node]:
                continue
            self.used[node] = True
            self.order = []
            self.dfs(node, self.graph_rev)
            #self.order.reverse()
            self.ans.append(self.order)

    def scc(self):
        self.first_dfs()
        self.second_dfs()
        return self.ans
        
def main():
    n,m = map(int,input().split())
    scc = SCC(n)
    for _ in range(m):
        a,b = map(int,input().split())
        scc.add_edge(a,b)

    ans = scc.scc()

    print(len(ans))
    for i in ans:
        print(len(i),*i)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)

class SCC:

    def __init__(self, n):
        self.n = n
        self.graph = [[] for i in range(n)]
        self.graph_rev = [[] for i in range(n)]
        self.used = [0]*n

    def add_edge(self, fr, to):
        if fr == to:
            return
        self.graph[fr].append(to)
        self.graph_rev[to].append(fr)

    def dfs(self, node, graph):
        self.used[node] = 1
        for nex in graph[node]:
            if self.used[nex]:
                continue
            self.dfs(nex,graph)
        self.order.append(node)

    def first_dfs(self):
        self.used = [0]*self.n
        self.order = []
        for i in range(self.n):
            if self.used[i]:
                continue
            self.dfs(i,self.graph)
    
    def second_dfs(self):
        self.used = [0]*self.n
        self.ans = []
        for node in reversed(self.order):
            if self.used[node]:
                continue
            self.used[node] = 1
            self.order = []
            self.dfs(node, self.graph_rev)
            self.order.reverse()
            self.ans.append(self.order)

    def scc(self):
        self.first_dfs()
        self.second_dfs()
        return self.ans
        
def main():
    n,m = map(int,input().split())
    scc = SCC(n)
    for _ in range(m):
        a,b = map(int,input().split())
        scc.add_edge(a,b)

    ans = scc.scc()

    print(len(ans))
    for i in ans:
        print(len(i),*i)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)

class SCC:

    def __init__(self, n):
        self.n = n
        self.graph = [[] for i in range(n)]
        self.graph_rev = [[] for i in range(n)]
        self.used = [False]*n

    def add_edge(self, fr, to):
        if fr == to:
            return
        self.graph[fr].append(to)
        self.graph_rev[to].append(fr)

    def dfs(self, node, graph):
        self.used[node] = True
        for nex in graph[node]:
            if self.used[nex]:
                continue
            self.dfs(nex,graph)
        self.order.append(node)

    def first_dfs(self):
        self.used = [False]*self.n
        self.order = []
        for i in range(self.n):
            if self.used[i]:
                continue
            self.dfs(i,self.graph)
    
    def second_dfs(self):
        self.used = [False]*self.n
        self.ans = []
        for node in reversed(self.order):
            if self.used[node]:
                continue
            self.used[node] = True
            self.order = []
            self.dfs(node, self.graph_rev)
            self.order.reverse()
            self.ans.append(self.order)

    def scc(self):
        self.first_dfs()
        self.second_dfs()
        return self.ans
        
def main():
    n,m = map(int,input().split())
    scc = SCC(n)
    for _ in range(m):
        a,b = map(int,input().split())
        scc.add_edge(a,b)

    ans = scc.scc()

    print(len(ans))
    for i in ans:
        print(len(i),*i)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)

class SCC:

    def __init__(self, n):
        self.n = n
        self.graph = [[] for i in range(n)]
        self.graph_rev = [[] for i in range(n)]
        self.used = [False]*n

    def add_edge(self, fr, to):
        if fr == to:
            return
        self.graph[fr].append(to)
        self.graph_rev[to].append(fr)

    def dfs(self, node, graph):
        self.used[node] = True
        for nex in graph[node]:
            if self.used[nex]:
                continue
            self.dfs(nex,graph)
        self.order.append(node)

    def first_dfs(self):
        self.used = [False]*self.n
        self.order = []
        for i in range(self.n):
            if self.used[i]:
                continue
            self.dfs(i,self.graph)
    
    def second_dfs(self):
        self.used = [False]*self.n
        self.ans = []
        for node in reversed(self.order):
            if self.used[node]:
                continue
            self.used[node] = True
            self.order = []
            self.dfs(node, self.graph_rev)
            self.order.reverse()
            self.ans.append(self.order)

    def scc(self):
        self.first_dfs()
        self.second_dfs()
        return self.ans
        

n,m = map(int,input().split())
scc = SCC(n)
for _ in range(m):
    a,b = map(int,input().split())
    scc.add_edge(a,b)

ans = scc.scc()

print(len(ans))
for i in ans:
    print(len(i),*i)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)


class StrongConnectedComponents:
    def __init__(self, n):
        self.n = n
        self.G = [[] for _ in range(n)]
        self.rG = [[] for _ in range(n)]
        self.cmp = [-1] * n

    def add_edge(self, frm, to):
        self.G[frm].append(to)
        self.rG[to].append(frm)

    def dfs(self, s):
        self.used[s] = 1
        for t in self.G[s]:
            if not self.used[t]:
                self.dfs(t)
        self.vs.append(s)

    def rdfs(self, s, k):
        self.used[s] = 1
        self.cmp[s] = k
        for t in self.rG[s]:
            if not self.used[t]:
                self.rdfs(t, k)

    def scc(self):
        self.vs = []
        self.used = [0] * self.n
        for v in range(self.n):
            if not self.used[v]:
                self.dfs(v)
        self.used = [0] * self.n
        k = 0
        for v in reversed(self.vs):
            if not self.used[v]:
                self.rdfs(v, k)
                k += 1
        return k, self.make_pair(k)

    def make_pair(self, k):
        res = [[] for _ in range(k)]
        for i, v in enumerate(self.cmp):
            res[v].append(i)
        return res


N, M = map(int, input().split())
g = StrongConnectedComponents(N)
for _ in range(M):
    a, b = map(int, input().split())
    g.add_edge(a, b)
label, group = g.scc()

print(label)
for x in group:
    print(len(x), end=" ")
    print(*x, sep=" ")

Submission status: Accepted

Solution code:
import sys
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
readlines=sys.stdin.buffer.readlines

def scc(g):
    n=len(g)
    cmp=[0]*n
    ord=[-1]*n
    fin=[False]*n
    low=[0]*n
    visited=[]
    num=0
    k=0
    for x in range(n):
        if ord[x]!=-1:
            continue
        st=[~x, x]
        while st:
            v=st.pop()
            if v>=0:
                if ord[v]!=-1:
                    continue
                ord[v]=num
                low[v]=num
                num+=1
                visited.append(v)
                for w in g[v]:
                    if ord[w]==-1:
                        st.append(~w)
                        st.append(w)
            else:
                v=~v
                if fin[v]:
                    continue
                fin[v]=True
                for w in g[v]:
                    if ord[w]<ord[v]:
                        if ord[w]<low[v]:
                            low[v]=ord[w]
                    elif ord[w]<n:
                        if low[w]<low[v]:
                            low[v]=low[w]
                if ord[v]==low[v]:
                    while True:
                        w=visited.pop()
                        cmp[w]=k
                        ord[w]=n
                        if w==v:
                            break
                    k+=1
    cmp=[k-1-x for x in cmp]
    return (k, cmp)
n, m=map(int, readline().split())
g=[[] for _ in range(n)]
ab=map(int, read().split())
for a, b in zip(ab, ab):
    g[a].append(b)
k, cmp=scc(g)
print(k)
vs=[[] for _ in range(k)]
ans=[]
for i, x in enumerate(cmp):
    vs[x].append(i)
for v in vs:
    ans.append(f"{len(v)} "+" ".join(map(str, v)))
print("\n".join(ans))

Submission status: Accepted

Solution code:
import types

_atcoder_code = """
# Python port of AtCoder Library.

__version__ = '0.0.1'
"""

atcoder = types.ModuleType('atcoder')
exec(_atcoder_code, atcoder.__dict__)

_atcoder__scc_code = """
import copy
import sys
import typing


class CSR:
    def __init__(
            self, n: int, edges: typing.List[typing.Tuple[int, int]]) -> None:
        self.start = [0] * (n + 1)
        self.elist = [0] * len(edges)

        for e in edges:
            self.start[e[0] + 1] += 1

        for i in range(1, n + 1):
            self.start[i] += self.start[i - 1]

        counter = copy.deepcopy(self.start)
        for e in edges:
            self.elist[counter[e[0]]] = e[1]
            counter[e[0]] += 1


class SCCGraph:
    '''
    Reference:
    R. Tarjan,
    Depth-First Search and Linear Graph Algorithms
    '''

    def __init__(self, n: int) -> None:
        self._n = n
        self._edges = []

    def num_vertices(self) -> int:
        return self._n

    def add_edge(self, from_vertex: int, to_vertex: int) -> None:
        self._edges.append((from_vertex, to_vertex))

    def scc_ids(self) -> typing.Tuple[int, typing.List[int]]:
        g = CSR(self._n, self._edges)
        now_ord = 0
        group_num = 0
        visited = []
        low = [0] * self._n
        order = [-1] * self._n
        ids = [0] * self._n

        sys.setrecursionlimit(max(self._n + 1000, sys.getrecursionlimit()))

        def dfs(v: int) -> None:
            nonlocal now_ord
            nonlocal group_num
            nonlocal visited
            nonlocal low
            nonlocal order
            nonlocal ids

            low[v] = now_ord
            order[v] = now_ord
            now_ord += 1
            visited.append(v)
            for i in range(g.start[v], g.start[v + 1]):
                to = g.elist[i]
                if order[to] == -1:
                    dfs(to)
                    low[v] = min(low[v], low[to])
                else:
                    low[v] = min(low[v], order[to])

            if low[v] == order[v]:
                while True:
                    u = visited[-1]
                    visited.pop()
                    order[u] = self._n
                    ids[u] = group_num
                    if u == v:
                        break
                group_num += 1

        for i in range(self._n):
            if order[i] == -1:
                dfs(i)

        for i in range(self._n):
            ids[i] = group_num - 1 - ids[i]

        return group_num, ids

    def scc(self) -> typing.List[typing.List[int]]:
        ids = self.scc_ids()
        group_num = ids[0]
        counts = [0] * group_num
        for x in ids[1]:
            counts[x] += 1
        groups = [[] for _ in range(group_num)]
        for i in range(self._n):
            groups[ids[1][i]].append(i)

        return groups
"""

atcoder._scc = types.ModuleType('atcoder._scc')
exec(_atcoder__scc_code, atcoder._scc.__dict__)


_atcoder_scc_code = """
import typing

# import atcoder._scc


class SCCGraph:
    def __init__(self, n: int = 0) -> None:
        self._internal = atcoder._scc.SCCGraph(n)

    def add_edge(self, from_vertex: int, to_vertex: int) -> None:
        n = self._internal.num_vertices()
        assert 0 <= from_vertex < n
        assert 0 <= to_vertex < n
        self._internal.add_edge(from_vertex, to_vertex)

    def scc(self) -> typing.List[typing.List[int]]:
        return self._internal.scc()
"""

atcoder.scc = types.ModuleType('atcoder.scc')
exec(_atcoder_scc_code, atcoder.scc.__dict__)
atcoder.scc.__dict__['atcoder'] = atcoder
atcoder.scc.__dict__['atcoder._scc'] = atcoder._scc
SCCGraph = atcoder.scc.SCCGraph

# https://atcoder.jp/contests/practice2/tasks/practice2_b

import sys

# from atcoder.scc import SCCGraph


def main() -> None:
    n, m = map(int, sys.stdin.readline().split())
    g = SCCGraph(n)

    for i in range(m):
        u, v = map(int, sys.stdin.readline().split())
        g.add_edge(u, v)

    scc = g.scc()

    print(len(scc))
    for v in scc:
        print(len(v), end='')
        for x in v:
            print(f' {x}', end='')
        print('')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
"""
scc の計算自体は 300～400ms程度。
あとは import と出力"""

import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8, i8[:, :], i8[:], i8[:], i8[:], i8[:], i8[:], i8, i8, i8, i8),
      cache=True)
def scc_dfs(N, G, idx, low, ord, ids, visited, now_ord, group_num, vis_i, v):
    low[v] = ord[v] = now_ord
    now_ord += 1
    visited[vis_i], vis_i = v, vis_i + 1
    for e in range(idx[v], idx[v + 1]):
        to = G[e, 1]
        if ord[to] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, to)
            low[v] = min(low[v], low[to])
        else:
            low[v] = min(low[v], ord[to])
    if low[v] == ord[v]:
        while True:
            u, vis_i = visited[vis_i - 1], vis_i - 1
            ord[u] = N
            ids[u] = group_num
            if u == v:
                break
        group_num += 1
    return now_ord, group_num, vis_i


@njit((i8, i8[:, :]), cache=True)
def scc(N, G):
    idx = np.searchsorted(G[:, 0], np.arange(N + 1))
    low = np.zeros(N, np.int64)
    ord = np.zeros(N, np.int64) - 1
    now_ord = 0
    group_num = 0
    visited, vis_i = np.empty(N, np.int64), 0
    ids = np.zeros(N, np.int64)
    for v in range(N):
        if ord[v] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, v)
    return group_num, group_num - ids - 1

@njit((i8, i8[:, :]), cache=True)
def main(N, G):
    n_comp, comp = scc(N, G)
    ans = np.empty((N, 2), np.int64)
    ans[:, 0] = np.arange(N)
    ans[:, 1] = comp
    ans = ans[np.argsort(ans[:, 1])]
    idx = np.searchsorted(ans[:, 1], np.arange(n_comp + 1))
    print(n_comp)
    for c in range(n_comp):
        V = ans[idx[c]:idx[c + 1], 0]
        print(len(V))
        for v in V:
            print(v)

N, M = map(int, readline().split())
AB = np.array(read().split(), np.int64).reshape(-1, 2)

AB = AB[np.argsort(AB[:, 0])]

main(N, AB)

Submission status: Accepted

Solution code:
import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8, i8[:, :], i8[:], i8[:], i8[:], i8[:], i8[:], i8, i8, i8, i8),
      cache=True)
def scc_dfs(N, G, idx, low, ord, ids, visited, now_ord, group_num, vis_i, v):
    low[v] = ord[v] = now_ord
    now_ord += 1
    visited[vis_i], vis_i = v, vis_i + 1
    for e in range(idx[v], idx[v + 1]):
        to = G[e, 1]
        if ord[to] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, to)
            low[v] = min(low[v], low[to])
        else:
            low[v] = min(low[v], ord[to])
    if low[v] == ord[v]:
        while True:
            u, vis_i = visited[vis_i - 1], vis_i - 1
            ord[u] = N
            ids[u] = group_num
            if u == v:
                break
        group_num += 1
    return now_ord, group_num, vis_i


@njit((i8, i8[:, :]), cache=True)
def scc(N, G):
    idx = np.searchsorted(G[:, 0], np.arange(N + 1))
    low = np.zeros(N, np.int64)
    ord = np.zeros(N, np.int64) - 1
    now_ord = 0
    group_num = 0
    visited, vis_i = np.empty(N, np.int64), 0
    ids = np.zeros(N, np.int64)
    for v in range(N):
        if ord[v] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, v)
    return group_num, group_num - ids - 1

@njit((i8, i8[:, :]), cache=True)
def main(N, G):
    n_comp, comp = scc(N, G)
    ans = np.empty((N, 2), np.int64)
    ans[:, 0] = np.arange(N)
    ans[:, 1] = comp
    ans = ans[np.argsort(ans[:, 1])]
    idx = np.searchsorted(ans[:, 1], np.arange(n_comp + 1))
    print(n_comp)
    for c in range(n_comp):
        V = ans[idx[c]:idx[c + 1], 0]
        print(len(V))
        for v in V:
            print(v)

N, M = map(int, readline().split())
AB = np.array(read().split(), np.int64).reshape(-1, 2)

AB = AB[np.argsort(AB[:, 0])]

main(N, AB)

Submission status: Accepted

Solution code:
import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8, i8[:, :], i8[:], i8[:], i8[:], i8[:], i8[:], i8, i8, i8, i8),
      cache=True)
def scc_dfs(N, G, idx, low, ord, ids, visited, now_ord, group_num, vis_i, v):
    low[v] = ord[v] = now_ord
    now_ord += 1
    visited[vis_i], vis_i = v, vis_i + 1
    for e in range(idx[v], idx[v + 1]):
        to = G[e, 1]
        if ord[to] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, to)
            low[v] = min(low[v], low[to])
        else:
            low[v] = min(low[v], ord[to])
    if low[v] == ord[v]:
        while True:
            u, vis_i = visited[vis_i - 1], vis_i - 1
            ord[u] = N
            ids[u] = group_num
            if u == v:
                break
        group_num += 1
    return now_ord, group_num, vis_i


@njit((i8, i8[:, :]), cache=True)
def scc(N, G):
    idx = np.searchsorted(G[:, 0], np.arange(N + 1))
    low = np.zeros(N, np.int64)
    ord = np.zeros(N, np.int64) - 1
    now_ord = 0
    group_num = 0
    visited, vis_i = np.empty(N, np.int64), 0
    ids = np.zeros(N, np.int64)
    for v in range(N):
        if ord[v] == -1:
            now_ord, group_num, vis_i = \
                scc_dfs(N, G, idx, low, ord, ids,
                        visited, now_ord, group_num,
                        vis_i, v)
    return group_num, group_num - ids - 1

def main(N, G):
    n_comp, comp = scc(N, G)
    ans = np.empty((N, 2), np.int64)
    ans[:, 0] = np.arange(N)
    ans[:, 1] = comp
    ans = ans[np.argsort(ans[:, 1])]
    idx = np.searchsorted(ans[:, 1], np.arange(n_comp + 1))
    print(n_comp)
    for c in range(n_comp):
        V = ans[idx[c]:idx[c + 1], 0]
        print(len(V), ' '.join(map(str, V)))

N, M = map(int, readline().split())
AB = np.array(read().split(), np.int64).reshape(-1, 2)

AB = AB[np.argsort(AB[:, 0])]

main(N, AB)