This page is still under construction.

Parts of this page are still being built. What you see may change.

Friendship Graph

Time limit2sMemory limit128 MB

Summary
Decide up to 200000 reachability queries on a directed graph with 2000 vertices, printing 1 when Y is reachable from X.
Level

Medium6 of 10

Topics
Graph, DFS, Topological sort, Bit manipulation
Solved
No attempts yet

Problem

Friendship between two people is usually mutual, but not always.

If person AA trusts person BB, the friendship graph GG has a directed edge A→BA \to B. GG can contain A→BA \to B without containing B→AB \to A.

Person XX wants to deliver a secret message to another person YY, either directly or by passing it along a chain of trusted friendships in GG. The message gets through exactly when you can start at XX, follow edges in their direction, and arrive at YY.

You are given QQ queries, each with its own XX and YY. Decide for every query whether the message gets through.

Input

The input has two parts. The first part is the friendship graph GG and the second part is the queries, separated by a blank line for clarity.

The first line contains two integers VV and EE. (1≤V≤20001 \le V \le 2000, 0≤E≤1000000 \le E \le 100000)

Each of the next EE lines contains two integers AA and BB, meaning GG has the directed edge A→BA \to B. Vertices are numbered from 00 to V−1V-1, so 0≤A,B<V0 \le A, B < V.

The next line contains the number of queries QQ. (1≤Q≤2000001 \le Q \le 200000)

Each of the next QQ lines contains two integers XX and YY. (0≤X,Y<V0 \le X, Y < V) A query with X=YX = Y can appear.

Output

Print one line per query. Print 1 if the message from XX reaches YY, and 0 if it does not. If X=YX = Y, print 1.

Examples1

  1. Example 1

    Input
    7 9
    0 1
    1 0
    1 3
    3 1
    1 2
    2 4
    4 5
    5 6
    6 4
    
    10
    0 1
    1 0
    0 2
    3 2
    2 0
    2 2
    2 6
    4 5
    5 6
    6 4
    
    Expected output
    1
    1
    1
    1
    0
    1
    1
    1
    1
    1