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 C (judge verdict: Accepted)

#include<stdio.h>
#include<stdlib.h>
struct node {
  int id;
  struct node* next;
};

struct node **list;
int *seq, *group, *stack, counter, phase, except,sp;

void Insert(int, int);
int strongcomponent(int);
int main(void)
{
  int i, v, e,s ,t, q;
  scanf("%d %d", &v, &e);
  list = (struct node**)malloc(sizeof(struct node*) * v);
  seq = (int*)calloc(v, sizeof(int));
  group = (int*)malloc(sizeof(int) * v);
  stack = (int*)malloc(sizeof(int) * v);
  except = v + 1;
  for (i = 0; i < v; i++) {
    list[i] = NULL;
    group[i] = -1;
  }
  for (i = 0; i < e; i++) {
    scanf("%d %d", &s, &t);
    Insert(s,t);
  }
  for (i = 0; i < v; i++) {
    if (!seq[i]) {
      strongcomponent(i);
    }
  }
  scanf("%d", &q);
  for (i = 0; i < q; i++) {
    scanf("%d %d", &s, &t);
    if (group[s] == group[t]) printf("1\n");
    else printf("0\n");
  }
  for (i = 0; i < v; i++) free(list[i]);
  free(seq);
  free(group);
  free(stack);
}
void Insert(int a, int b)
{
  struct node *p = (struct node*)malloc(sizeof(struct node));
  p->id = b;
  p->next = list[a];
  list[a] = p;
}
int strongcomponent(int point)
{
  int min;
  struct node *n;
  counter++;
  min = seq[point] = counter;
  stack[sp++] = point;
  for (n = list[point]; n != NULL; n = n->next) {
    int m;
    if (!seq[n->id]) m = strongcomponent(n->id);
    else m = seq[n->id];
    if (m < min) min = m;
  }
  if (min == seq[point]) {
    int x;
    do {
      sp--;
      x = stack[sp];
      group[x] = phase;
      seq[x] = except;
    } while (x != point);
    phase++;
  }
  return min;
}