Problem:
Strongly Connected Components

A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.

Input

A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.

|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1

|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target nodes of i-th edge (directed).

ui and vi represent a pair of nodes given as the i-th query.

Output

For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.

Constraints

1 ≤ |V| ≤ 10,000

0 ≤ |E| ≤ 30,000

1 ≤ Q ≤ 100,000

Sample Input 1

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

Sample Output 1

1
0
1
1

Solution in Rust (judge verdict: Accepted)

//! ----------------------------------------------
//! Framework <https://github.com/vain0x/procon>
//!
//! See the bottom of file for solution.
//! ----------------------------------------------

#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Display, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

/// Print values to standard error if debug mode.
#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), stderr());
            writeln!(err, "\x1B[33m{}\x1B[0m = {:?}", e, $e).unwrap()
        })*
    };
}

/// Read from standard input and parse each word.
/// - `read!(T, U, ..)` parses a line as a tuple of words.
/// - `read![[T]]` parses a line as an array of words.
/// - `read![..; N]` parses `N` lines, using `read!(..)` repeatedly.
#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

/// Read a line from standard input.
#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();

    #[allow(deprecated)]
    buf.trim_right().to_owned()
}

// -----------------------------------------------
// Solution
// -----------------------------------------------

struct StrongComponentDecomposition {
    /// Number of vertices.
    N: usize,
    /// The graph.
    G: Rc<Vec<Vec<usize>>>,
    /// Dual of the graph
    H: Rc<Vec<Vec<usize>>>,
    /// gray[u] = true if the vertex u is visited.
    gray: Vec<bool>,
    /// Topological order index for each vertex.
    top_ord: Vec<usize>,
    /// List of vertices in topological order.
    top_seq: Vec<usize>,
    /// Next index of topological order.
    next_ord: usize,
    /// Output of the process.
    components: Vec<Vec<usize>>,
}

impl StrongComponentDecomposition {
    fn run(G: Rc<Vec<Vec<usize>>>) -> Vec<Vec<usize>> {
        let N = G.len();
        let mut H = vec![vec![]; N];
        for u in 0..N {
            for &v in &G[u] {
                H[v].push(u);
            }
        }

        let it = StrongComponentDecomposition {
            N: N,
            G: Rc::clone(&G),
            H: Rc::new(H),
            gray: vec![],
            top_ord: vec![N; N],
            top_seq: vec![],
            next_ord: 0,
            components: vec![],
        };
        it.start()
    }

    fn start(mut self) -> Vec<Vec<usize>> {
        self.gray = vec![false; self.N];
        for u in 0..self.N {
            self.top(u);
        }

        self.gray = vec![false; self.N];
        let mut vertices = std::mem::replace(&mut self.top_seq, vec![]);
        vertices.reverse();
        for u in vertices {
            if self.gray[u] {
                continue;
            }

            let mut component = vec![];
            self.bot(&mut component, u);
            self.components.push(component);
        }

        self.components
    }

    /// Topological sort.
    fn top(&mut self, u: usize) {
        if self.gray[u] {
            return;
        }
        self.gray[u] = true;

        for &v in Rc::clone(&self.G)[u].iter() {
            self.top(v);
        }

        self.top_seq.push(u);
        self.top_ord[u] = self.next_ord;
        self.next_ord += 1;
    }

    /// DFS over the dual.
    fn bot(&mut self, c: &mut Vec<usize>, u: usize) {
        if self.gray[u] {
            return;
        }

        self.gray[u] = true;
        c.push(u);

        for &v in Rc::clone(&self.H)[u].iter() {
            self.bot(c, v);
        }
    }
}

fn main() {
    let (N, M) = read!(usize, usize);
    let T = read![usize, usize; M];
    let q = read!(usize);
    let Q = read![usize, usize; q];

    let mut G = vec![vec![]; N];
    for (u, v) in T {
        G[u].push(v);
    }

    let components = StrongComponentDecomposition::run(Rc::new(G));
    debug!(components);
    let mut roots = vec![0; N];
    for c in components {
        let u = c[0];
        for v in c {
            roots[v] = u;
        }
    }
    debug!(roots);

    for (u, v) in Q {
        println!("{}", if roots[u] == roots[v] { 1 } else { 0 });
    }
}