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

Solution in Rust (1.42.0) (judge verdict: Accepted)

#[allow(unused_imports)]
use itertools::Itertools;
#[allow(unused_imports)]
use itertools_num::ItertoolsNum;
#[allow(unused_imports)]
use std::cmp;
#[allow(unused_imports)]
use std::iter;
#[allow(unused_imports)]
use superslice::*;

pub struct Csr<E> {
    start: Vec<usize>,
    elist: Vec<E>,
}

impl<E> Csr<E>
where
    E: Clone + Copy,
{
    pub fn new(n: usize, edges: &[(usize, E)], init: E) -> Self {
        let mut csr = Csr {
            start: vec![0usize; n + 1],
            elist: vec![init; edges.len()],
        };
        for e in edges.iter() {
            csr.start[e.0 + 1] += 1;
        }
        for i in 1..=n {
            csr.start[i] += csr.start[i - 1];
        }
        let mut counter = csr.start.clone();
        for e in edges.iter() {
            csr.elist[counter[e.0]] = e.1;
            counter[e.0] += 1;
        }
        csr
    }
}

pub struct SccGraph {
    n: usize,
    edges: Vec<(usize, _Edge)>,
}

impl SccGraph {
    pub fn new(n: usize) -> Self {
        SccGraph { n, edges: vec![] }
    }

    pub fn num_vertices(&self) -> usize {
        self.n
    }

    pub fn add_edge(&mut self, from: usize, to: usize) {
        self.edges.push((from, _Edge { to }));
    }

    pub fn scc_ids(&self) -> (usize, Vec<usize>) {
        let g = Csr::new(self.n, &self.edges, _Edge { to: 0 });
        let mut now_ord = 0usize;
        let mut group_num = 0usize;
        let mut visited = Vec::with_capacity(self.n);
        let mut low = vec![0; self.n];
        let mut ord = vec![None; self.n];
        let mut ids = vec![0; self.n];

        fn dfs(
            v: usize,
            n: usize,
            g: &Csr<_Edge>,
            now_ord: &mut usize,
            group_num: &mut usize,
            visited: &mut Vec<usize>,
            low: &mut Vec<usize>,
            ord: &mut Vec<Option<usize>>,
            ids: &mut Vec<usize>,
        ) {
            low[v] = *now_ord;
            ord[v] = Some(*now_ord);
            *now_ord += 1;
            visited.push(v);

            for i in g.start[v]..g.start[v + 1] {
                let to = g.elist[i].to;
                if ord[to].is_none() {
                    dfs(to, n, g, now_ord, group_num, visited, low, ord, ids);
                    low[v] = std::cmp::min(low[v], low[to]);
                } else {
                    low[v] = std::cmp::min(low[v], ord[to].unwrap());
                }
            }
            if low[v] == ord[v].unwrap() {
                loop {
                    let u = *visited.last().unwrap();
                    visited.pop();
                    ord[u] = Some(n);
                    ids[u] = *group_num;
                    if u == v {
                        break;
                    }
                }
                *group_num += 1;
            }
        }

        for i in 0..self.n {
            if ord[i].is_none() {
                dfs(
                    i,
                    self.n,
                    &g,
                    &mut now_ord,
                    &mut group_num,
                    &mut visited,
                    &mut low,
                    &mut ord,
                    &mut ids,
                );
            }
        }

        for x in ids.iter_mut() {
            *x = group_num - 1 - *x;
        }

        (group_num, ids)
    }

    pub fn scc(&self) -> Vec<Vec<usize>> {
        let ids = self.scc_ids();
        let group_num = ids.0;
        let mut counts = vec![0usize; group_num];
        for &x in ids.1.iter() {
            counts[x] += 1;
        }
        let mut groups: Vec<Vec<usize>> = (0..ids.0).map(|_| vec![]).collect();
        for i in 0..group_num {
            groups[i].reserve(counts[i]);
        }
        for i in 0..self.n {
            groups[ids.1[i]].push(i);
        }
        groups
    }
}

#[derive(Copy, Clone)]
struct _Edge {
    to: usize,
}

struct SccGraphO {
    internal: SccGraph,
}

impl SccGraphO {
    pub fn new(n: usize) -> Self {
        SccGraphO {
            internal: SccGraph::new(n),
        }
    }

    pub fn add_edge(&mut self, from: usize, to: usize) {
        let n = self.internal.num_vertices();
        assert!(from < n);
        assert!(to < n);
        self.internal.add_edge(from, to);
    }

    pub fn scc(&self) -> Vec<Vec<usize>> {
        self.internal.scc()
    }
}

fn run() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());

    let n: usize = sc.read();
    let m: usize = sc.read();

    let mut g = SccGraphO::new(n);
    for _ in 0..m {
        let u: usize = sc.read();
        let v: usize = sc.read();
        g.add_edge(u, v);
    }

    let scc = g.scc();
    println!("{}", scc.len());
    for c in scc.into_iter() {
        print!("{}", c.len());
        for v in c.into_iter() {
            print!(" {}", v);
        }
        println!("");
    }
}

fn main() {
    std::thread::Builder::new()
        .name("run".into())
        .stack_size(256 * 1024 * 1024)
        .spawn(run)
        .unwrap()
        .join()
        .unwrap();
}

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> IO<R, W> {
        IO(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: std::ops::Deref<Target = str>>(&mut self, s: S) {
        use std::io::Write;
        self.1.write(s.as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn read_vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn read_pairs<T: std::str::FromStr>(&mut self, n: usize) -> Vec<(T, T)> {
        (0..n).map(|_| (self.read(), self.read())).collect()
    }
    pub fn read_pairs_1_indexed(&mut self, n: usize) -> Vec<(usize, usize)> {
        (0..n)
            .map(|_| (self.read::<usize>() - 1, self.read::<usize>() - 1))
            .collect()
    }
    pub fn read_chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
    pub fn read_char_grid(&mut self, n: usize) -> Vec<Vec<char>> {
        (0..n).map(|_| self.read_chars()).collect()
    }
    pub fn read_matrix<T: std::str::FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<T>> {
        (0..n)
            .map(|_| (0..m).map(|_| self.read()).collect())
            .collect()
    }
}