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)

// template {{{
#![allow(clippy::many_single_char_names)]

#[allow(dead_code)]
mod ngtio {
    use ::std::collections::VecDeque;

    pub struct Buffer {
        buf: VecDeque<String>,
    }

    impl Buffer {
        pub fn new() -> Self {
            Self {
                buf: VecDeque::new(),
            }
        }

        fn load(&mut self) {
            while self.buf.is_empty() {
                let mut s = String::new();
                let length = ::std::io::stdin().read_line(&mut s).unwrap();
                if length == 0 {
                    break;
                }
                self.buf.extend(s.split_whitespace().map(|s| s.to_owned()));
            }
        }

        pub fn string(&mut self) -> String {
            self.load();
            self.buf
                .pop_front()
                .unwrap_or_else(|| panic!("入力が終了したのですが。"))
        }

        pub fn string_char_vec(&mut self) -> Vec<char> {
            let s = self.string();
            s.chars().collect::<Vec<_>>()
        }

        pub fn string_char_vec_trusted_len(&mut self, len: usize) -> Vec<char> {
            let s = self.string();
            let s = s.chars().collect::<Vec<_>>();
            assert_eq!(s.len(), len, "あら、思ったのと長さ違いますね……");
            s
        }

        pub fn char(&mut self) -> char {
            let string = self.string();
            let mut chars = string.chars();
            let res = chars.next().unwrap();
            assert!(
                chars.next().is_none(),
                "char で受け取りたいのも山々なのですが、さては 2 文字以上ありますね？"
            );
            res
        }

        pub fn read<T: ::std::str::FromStr>(&mut self) -> T
        where
            <T as ::std::str::FromStr>::Err: ::std::fmt::Debug,
        {
            self.string()
                .parse::<T>()
                .expect("Failed to parse the input.")
        }

        pub fn read_vec<T: ::std::str::FromStr>(&mut self, len: usize) -> Vec<T>
        where
            <T as ::std::str::FromStr>::Err: ::std::fmt::Debug,
        {
            (0..len).map(|_| self.read::<T>()).collect()
        }
    }

    macro_rules! define_primitive_reader {
        ($($ty:tt,)*) => {
            impl Buffer {
                $(
#[inline]
                    pub fn $ty(&mut self) -> $ty {
                        self.read::<$ty>()
                    }
                )*
            }
        }
    }

    define_primitive_reader! {
        u8, u16, u32, u64, usize,
        i8, i16, i32, i64, isize,
    }

    impl Default for Buffer {
        fn default() -> Self {
            Self::new()
        }
    }
}

#[allow(unused_imports)]
use std::{collections, iter, mem, ops};
// }}}
// scc {{{
#[allow(dead_code)]
mod scc {
    mod traversal {
        use std::mem;

        #[derive(Debug, Clone)]
        pub struct Traversal {
            pub index: Vec<usize>,
            pub time: Vec<usize>,
        }

        impl Traversal {
            pub fn pre_order(graph: &[Vec<usize>]) -> Traversal {
                fn dfs(x: usize, graph: &[Vec<usize>], res: &mut PermutationBuilder) {
                    res.visit(x);
                    for &y in &graph[x] {
                        if !res.on_stack(y) {
                            dfs(y, graph, res);
                        }
                    }
                }

                let mut res = PermutationBuilder::new(graph.len());
                for i in 0..graph.len() {
                    if !res.on_stack(i) {
                        dfs(i, &graph, &mut res);
                    }
                }
                res.build()
            }

            pub fn post_order(graph: &[Vec<usize>]) -> Traversal {
                fn dfs(
                    x: usize,
                    graph: &[Vec<usize>],
                    ckd: &mut [bool],
                    res: &mut PermutationBuilder,
                ) {
                    for &y in &graph[x] {
                        if !mem::replace(&mut ckd[y], true) {
                            dfs(y, graph, ckd, res);
                        }
                    }
                    res.visit(x);
                }

                let n = graph.len();
                let mut ckd = vec![false; n];
                let mut res = PermutationBuilder::new(graph.len());
                for i in 0..graph.len() {
                    if !mem::replace(&mut ckd[i], true) {
                        dfs(i, &graph, &mut ckd, &mut res);
                    }
                }
                res.build()
            }
        }

        #[derive(Debug, Clone)]
        struct PermutationBuilder {
            index: Vec<usize>,
            time: Vec<usize>,
        }

        impl PermutationBuilder {
            fn new(n: usize) -> Self {
                Self {
                    index: Vec::with_capacity(n),
                    time: vec![n; n],
                }
            }

            fn build(self) -> Traversal {
                Traversal {
                    index: self.index,
                    time: self.time,
                }
            }

            #[allow(dead_code)]
            fn is_empty(&self) -> bool {
                self.time.is_empty()
            }

            fn len(&self) -> usize {
                self.time.len()
            }

            fn time(&self) -> usize {
                self.index.len()
            }

            fn visit(&mut self, x: usize) {
                assert!(!self.on_stack(x));
                self.time[x] = self.time();
                self.index.push(x);
            }

            fn on_stack(&self, x: usize) -> bool {
                self.time[x] != self.len()
            }
        }
    }
    mod white_stack {
        #[derive(Debug, Clone)]
        pub struct WhiteStack {
            pub on_stack: Vec<bool>,
            pub stack: Vec<usize>,
        }

        impl WhiteStack {
            pub fn new(len: usize) -> Self {
                Self {
                    on_stack: vec![false; len],
                    stack: Vec::with_capacity(len),
                }
            }

            pub fn push(&mut self, i: usize) {
                assert!(i < self.on_stack.len());
                assert!(!self.on_stack[i]);
                self.on_stack[i] = true;
                self.stack.push(i);
            }

            pub fn pop(&mut self) -> Option<usize> {
                if let Some(i) = self.stack.pop() {
                    assert!(self.on_stack[i]);
                    Some(i)
                } else {
                    None
                }
            }

            pub fn peek(&self) -> Option<&usize> {
                self.stack.last()
            }
        }
    }

    // TODO: この2つは別ライブラリに切り出しても良いかもです。
    pub use traversal::*;
    pub use white_stack::*;

    use std::cmp;

    #[derive(Debug, Clone)]
    pub struct Scc {
        forward: Vec<Vec<usize>>, // TODO: フラットグラフも試します。
        backward: Vec<Vec<usize>>,
    }

    impl Scc {
        pub fn new(len: usize) -> Self {
            Self {
                forward: vec![Vec::new(); len],
                backward: vec![Vec::new(); len],
            }
        }
        pub fn add_edge(&mut self, u: usize, v: usize) {
            self.forward[u].push(v);
            self.backward[v].push(u);
        }
        pub fn solve(&self) -> (usize, Vec<usize>) {
            fn dfs(x: usize, g: &[Vec<usize>], res: &mut [Option<usize>]) {
                for &y in &g[x] {
                    if res[y].is_none() {
                        res[y] = res[x];
                        dfs(y, g, res);
                    }
                }
            }
            let n = self.forward.len();
            let post_backward = Traversal::post_order(&self.backward);
            let mut res = vec![None; n];
            let mut counter = 0;
            for &x in post_backward.index.iter().rev() {
                if res[x].is_none() {
                    res[x] = Some(counter);
                    dfs(x, &self.forward, &mut res);
                    counter += 1;
                }
            }
            (
                counter,
                res.iter().map(|x| counter - 1 - x.unwrap()).collect(),
            )
        }
        // TODO: 答えをいい感じにキャッシュするようにしても良いかもです。
        pub fn groups(&self) -> Vec<Vec<usize>> {
            let (count, id) = self.solve();
            let mut res = vec![Vec::new(); count];
            for (i, &x) in id.iter().enumerate() {
                res[x].push(i);
            }
            res
        }
    }

    #[derive(Debug, Clone)]
    pub struct TwoSat {
        len: usize,
        scc: Scc,
    }
    impl TwoSat {
        pub fn new(len: usize) -> Self {
            Self {
                len,
                scc: Scc::new(2 * len),
            }
        }
        pub fn add_clause(&mut self, i: usize, f: bool, j: usize, g: bool) {
            self.scc.add_edge(2 * i + !f as usize, 2 * j + g as usize);
            self.scc.add_edge(2 * j + !g as usize, 2 * i + f as usize);
        }
        pub fn solve(&mut self) -> Option<Vec<bool>> {
            self.scc
                .solve()
                .1
                .chunks_exact(2)
                .map(|v| {
                    use cmp::Ordering::*;
                    match v[0].cmp(&v[1]) {
                        Equal => None,
                        Less => Some(true),
                        Greater => Some(false),
                    }
                })
                .collect()
        }
    }
}
// }}}
// seq {{{
#[allow(dead_code)]
mod seq {
    #![warn(missing_docs, missing_doc_code_examples)]

    pub use self::accumulate::{accumulate, Accumulate};
    pub use self::adjacent::{adjacent, Adjacent};
    pub use self::cartesian_product::{cartesian_product, CartesianProduct};
    pub use self::format_intersparse::format_intersparse;
    pub use self::grid_next::{grid_next, GridNext};
    pub use self::intersperse::{intersperse, Intersperse};
    pub use self::mul_step::{mul_step, MulStep};
    pub use self::repeat_with::{repeat_with, RepeatWith};
    pub use self::step::{step, Step};

    use std::{fmt, ops};

    impl<I: Iterator> Seq for I {}

    pub trait Seq: Iterator + Sized {
        fn adjacent(self) -> Adjacent<Self, Self::Item>
        where
            Self::Item: Clone,
        {
            adjacent(self)
        }

        fn grid_next(self, ij: (usize, usize), h: usize, w: usize) -> GridNext<Self>
        where
            Self: Iterator<Item = (i64, i64)>,
        {
            grid_next(self, ij, h, w)
        }

        fn cartesian_product<J>(self, other: J) -> CartesianProduct<Self, J::IntoIter>
        where
            Self: Sized,
            Self::Item: Clone,
            J: IntoIterator,
            J::IntoIter: Clone,
        {
            cartesian_product::cartesian_product(self, other.into_iter())
        }

        fn accumulate<T>(self, init: T) -> Accumulate<Self, T>
        where
            T: Clone + ops::AddAssign<Self::Item>,
        {
            accumulate::accumulate(self, init)
        }

        fn intersperse(self, elt: Self::Item) -> Intersperse<Self> {
            intersperse::intersperse(self, elt)
        }

        fn format_intersparse<T>(self, separator: T) -> String
        where
            Self::Item: fmt::Display,
            T: fmt::Display,
        {
            self.map(|x| format!("{}", x))
                .intersperse(format!("{}", separator))
                .collect::<String>()
        }
    }

    mod adjacent {
        #[allow(missing_docs)]
        pub fn adjacent<I, T>(mut iter: I) -> Adjacent<I, T>
        where
            I: Iterator<Item = T>,
            T: Clone,
        {
            if let Some(first) = iter.next() {
                Adjacent {
                    iter,
                    prv: Some(first),
                }
            } else {
                Adjacent { iter, prv: None }
            }
        }

        #[allow(missing_docs)]
        pub struct Adjacent<I, T>
        where
            I: Iterator<Item = T>,
        {
            iter: I,
            prv: Option<T>,
        }

        impl<I, T> Iterator for Adjacent<I, T>
        where
            I: Iterator<Item = T>,
            T: Clone,
        {
            type Item = (T, T);

            fn next(&mut self) -> Option<(T, T)> {
                self.prv.as_ref().cloned().and_then(|first| {
                    self.iter.next().map(|second| {
                        self.prv = Some(second.clone());
                        (first, second)
                    })
                })
            }
        }
    }

    mod grid_next {
        #[allow(missing_docs)]
        pub fn grid_next<T>(difference: T, ij: (usize, usize), h: usize, w: usize) -> GridNext<T>
        where
            T: Iterator<Item = (i64, i64)>,
        {
            GridNext {
                i: ij.0 as i64,
                j: ij.1 as i64,
                h: h as i64,
                w: w as i64,
                difference,
            }
        }

        #[allow(missing_docs)]
        #[derive(Debug, Clone)]
        pub struct GridNext<T> {
            i: i64,
            j: i64,
            h: i64,
            w: i64,
            difference: T,
        }

        impl<T> Iterator for GridNext<T>
        where
            T: Iterator<Item = (i64, i64)>,
        {
            type Item = (usize, usize);

            fn next(&mut self) -> Option<(usize, usize)> {
                while let Some((di, dj)) = self.difference.next() {
                    let ni = self.i + di;
                    let nj = self.j + dj;
                    if 0 <= ni && ni < self.h && 0 <= nj && nj < self.w {
                        return Some((ni as usize, nj as usize));
                    }
                }
                None
            }
        }
    }

    mod step {
        #[allow(missing_docs)]
        pub fn step<T, U>(init: T, step: U) -> Step<T, U>
        where
            T: Copy,
            U: Copy,
            T: ::std::ops::Add<U, Output = T>,
        {
            Step { now: init, step }
        }

        #[allow(missing_docs)]
        #[derive(Debug, Clone)]
        pub struct Step<T, U> {
            now: T,
            step: U,
        }

        #[allow(missing_docs)]
        impl<T, U> Iterator for Step<T, U>
        where
            T: Copy,
            U: Copy,
            T: ::std::ops::Add<U, Output = T>,
        {
            type Item = T;

            fn next(&mut self) -> Option<T> {
                let next = self.now + self.step;
                Some(::std::mem::replace(&mut self.now, next))
            }
        }
    }

    mod mul_step {
        #[allow(missing_docs)]
        pub fn mul_step<T, U>(init: T, step: U) -> MulStep<T, U>
        where
            T: Copy,
            U: Copy,
            T: ::std::ops::Mul<U, Output = T>,
        {
            MulStep { now: init, step }
        }

        #[allow(missing_docs)]
        #[derive(Debug, Clone)]
        pub struct MulStep<T, U> {
            now: T,
            step: U,
        }

        #[allow(missing_docs)]
        impl<T, U> Iterator for MulStep<T, U>
        where
            T: Copy,
            U: Copy,
            T: ::std::ops::Mul<U, Output = T>,
        {
            type Item = T;

            fn next(&mut self) -> Option<T> {
                let next = self.now * self.step;
                Some(::std::mem::replace(&mut self.now, next))
            }
        }
    }

    mod repeat_with {
        #[allow(missing_docs)]
        pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
            RepeatWith { repeater }
        }

        #[allow(missing_docs)]
        #[derive(Debug, Clone)]
        pub struct RepeatWith<F> {
            repeater: F,
        }

        impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
            type Item = A;

            #[inline]
            fn next(&mut self) -> Option<A> {
                Some((self.repeater)())
            }

            #[inline]
            fn size_hint(&self) -> (usize, Option<usize>) {
                (::std::usize::MAX, None)
            }
        }
    }

    mod accumulate {
        use super::*;

        #[allow(missing_docs)]
        #[derive(Debug, Clone)]
        pub struct Accumulate<I, T> {
            prev: Option<T>,
            iter: I,
        }

        #[allow(missing_docs)]
        pub fn accumulate<I, T>(iter: I, init: T) -> Accumulate<I, T>
        where
            I: Iterator,
            T: Clone + ops::AddAssign<I::Item>,
        {
            Accumulate {
                prev: Some(init),
                iter,
            }
        }

        impl<I, T> Iterator for Accumulate<I, T>
        where
            I: Iterator,
            T: Clone + ops::AddAssign<I::Item>,
        {
            type Item = T;

            fn next(&mut self) -> Option<T> {
                let res = self.prev.clone();
                if let Some(prev) = self.prev.as_mut() {
                    if let Some(next) = self.iter.next() {
                        *prev += next;
                    } else {
                        self.prev = None;
                    }
                }
                res
            }

            fn size_hint(&self) -> (usize, Option<usize>) {
                size_hint::add_scalar(self.iter.size_hint(), 1)
            }
        }
    }

    mod cartesian_product {
        #[allow(missing_docs)]
        #[derive(Debug, Clone)]
        pub struct CartesianProduct<I, J>
        where
            I: Iterator,
        {
            a: I,
            a_cur: Option<I::Item>,
            b: J,
            b_orig: J,
        }

        #[allow(missing_docs)]
        pub fn cartesian_product<I, J>(mut i: I, j: J) -> CartesianProduct<I, J>
        where
            I: Iterator,
            J: Clone + Iterator,
            I::Item: Clone,
        {
            CartesianProduct {
                a_cur: i.next(),
                a: i,
                b_orig: j.clone(),
                b: j,
            }
        }

        impl<I, J> Iterator for CartesianProduct<I, J>
        where
            I: Iterator,
            J: Clone + Iterator,
            I::Item: Clone,
        {
            type Item = (I::Item, J::Item);

            fn next(&mut self) -> Option<(I::Item, J::Item)> {
                let elt_b = match self.b.next() {
                    None => {
                        self.b = self.b_orig.clone();
                        match self.b.next() {
                            None => return None,
                            Some(x) => {
                                self.a_cur = self.a.next();
                                x
                            }
                        }
                    }
                    Some(x) => x,
                };
                match self.a_cur {
                    None => None,
                    Some(ref a) => Some((a.clone(), elt_b)),
                }
            }

            fn size_hint(&self) -> (usize, Option<usize>) {
                let has_cur = self.a_cur.is_some() as usize;
                // Not ExactSizeIterator because size may be larger than usize
                let (b_min, b_max) = self.b.size_hint();

                // Compute a * b_orig + b for both lower and upper bound
                super::size_hint::add(
                    super::size_hint::mul(self.a.size_hint(), self.b_orig.size_hint()),
                    (b_min * has_cur, b_max.map(move |x| x * has_cur)),
                )
            }

            fn fold<Acc, G>(mut self, mut accum: Acc, mut f: G) -> Acc
            where
                G: FnMut(Acc, Self::Item) -> Acc,
            {
                if let Some(mut a) = self.a_cur.take() {
                    let mut b = self.b;
                    loop {
                        accum = b.fold(accum, |acc, elt| f(acc, (a.clone(), elt)));

                        // we can only continue iterating a if we had a first element;
                        if let Some(next_a) = self.a.next() {
                            b = self.b_orig.clone();
                            a = next_a;
                        } else {
                            break;
                        }
                    }
                }
                accum
            }
        }
    }

    #[allow(missing_docs)]
    mod intersperse {
        use super::size_hint;
        use std::iter;

        #[derive(Debug, Clone)]
        #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
        pub struct Intersperse<I>
        where
            I: Iterator,
        {
            element: I::Item,
            iter: iter::Fuse<I>,
            peek: Option<I::Item>,
        }

        pub fn intersperse<I>(iter: I, elt: I::Item) -> Intersperse<I>
        where
            I: Iterator,
        {
            let mut iter = iter.fuse();
            Intersperse {
                peek: iter.next(),
                iter,
                element: elt,
            }
        }

        impl<I> Iterator for Intersperse<I>
        where
            I: Iterator,
            I::Item: Clone,
        {
            type Item = I::Item;
            #[inline]
            fn next(&mut self) -> Option<I::Item> {
                if self.peek.is_some() {
                    self.peek.take()
                } else {
                    self.peek = self.iter.next();
                    if self.peek.is_some() {
                        Some(self.element.clone())
                    } else {
                        None
                    }
                }
            }

            fn size_hint(&self) -> (usize, Option<usize>) {
                // 2 * SH + { 1 or 0 }
                let has_peek = self.peek.is_some() as usize;
                let sh = self.iter.size_hint();
                size_hint::add_scalar(size_hint::add(sh, sh), has_peek)
            }

            fn fold<B, F>(mut self, init: B, mut f: F) -> B
            where
                Self: Sized,
                F: FnMut(B, Self::Item) -> B,
            {
                let mut accum = init;

                if let Some(x) = self.peek.take() {
                    accum = f(accum, x);
                }

                let element = &self.element;

                self.iter.fold(accum, |accum, x| {
                    let accum = f(accum, element.clone());
                    f(accum, x)
                })
            }
        }
    }

    #[allow(missing_docs)]
    mod format_intersparse {
        use super::Seq;
        use std::fmt;

        pub fn format_intersparse<I, T>(iter: I, separator: T) -> String
        where
            I: Iterator,
            I::Item: fmt::Display,
            T: fmt::Display,
        {
            iter.map(|x| format!("{}", x))
                .intersperse(format!("{}", separator))
                .collect::<String>()
        }
    }

    mod size_hint {

        use std::cmp;
        use std::usize;

        pub type SizeHint = (usize, Option<usize>);

        #[inline]
        pub fn add(a: SizeHint, b: SizeHint) -> SizeHint {
            let min = a.0.saturating_add(b.0);
            let max = match (a.1, b.1) {
                (Some(x), Some(y)) => x.checked_add(y),
                _ => None,
            };

            (min, max)
        }

        #[inline]
        #[allow(dead_code)]
        pub fn add_scalar(sh: SizeHint, x: usize) -> SizeHint {
            let (mut low, mut hi) = sh;
            low = low.saturating_add(x);
            hi = hi.and_then(|elt| elt.checked_add(x));
            (low, hi)
        }

        #[inline]
        #[allow(dead_code)]
        pub fn sub_scalar(sh: SizeHint, x: usize) -> SizeHint {
            let (mut low, mut hi) = sh;
            low = low.saturating_sub(x);
            hi = hi.map(|elt| elt.saturating_sub(x));
            (low, hi)
        }

        #[inline]
        #[allow(dead_code)]
        pub fn mul(a: SizeHint, b: SizeHint) -> SizeHint {
            let low = a.0.saturating_mul(b.0);
            let hi = match (a.1, b.1) {
                (Some(x), Some(y)) => x.checked_mul(y),
                (Some(0), None) | (None, Some(0)) => Some(0),
                _ => None,
            };
            (low, hi)
        }

        #[inline]
        #[allow(dead_code)]
        pub fn mul_scalar(sh: SizeHint, x: usize) -> SizeHint {
            let (mut low, mut hi) = sh;
            low = low.saturating_mul(x);
            hi = hi.and_then(|elt| elt.checked_mul(x));
            (low, hi)
        }

        #[inline]
        #[allow(dead_code)]
        pub fn max(a: SizeHint, b: SizeHint) -> SizeHint {
            let (a_lower, a_upper) = a;
            let (b_lower, b_upper) = b;

            let lower = cmp::max(a_lower, b_lower);

            let upper = match (a_upper, b_upper) {
                (Some(x), Some(y)) => Some(cmp::max(x, y)),
                _ => None,
            };

            (lower, upper)
        }

        #[inline]
        #[allow(dead_code)]
        pub fn min(a: SizeHint, b: SizeHint) -> SizeHint {
            let (a_lower, a_upper) = a;
            let (b_lower, b_upper) = b;
            let lower = cmp::min(a_lower, b_lower);
            let upper = match (a_upper, b_upper) {
                (Some(u1), Some(u2)) => Some(cmp::min(u1, u2)),
                _ => a_upper.or(b_upper),
            };
            (lower, upper)
        }
    }
}
// }}}

use seq::Seq;

fn main() {
    let mut buf = ngtio::Buffer::new();
    let n = buf.usize();
    let mut scc = scc::Scc::new(n);
    for _ in 0..buf.usize() {
        let u = buf.usize();
        let v = buf.usize();
        scc.add_edge(u, v);
    }
    let ans = scc.groups();
    println!("{}", ans.len());
    for v in &ans {
        println!("{} {}", v.len(), v.iter().format_intersparse(' '));
    }
}