Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Connected Components

Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.

Input

In the first line, two integer $n$ and $m$ are given. $n$ is the number of users in the SNS and $m$ is the number of relations in the SNS. The users in the SNS are identified by IDs $0, 1, ..., n-1$.

In the following $m$ lines, the relations are given. Each relation is given by two integers $s$ and $t$ that represents $s$ and $t$ are friends (and reachable each other).

In the next line, the number of queries $q$ is given. In the following $q$ lines, $q$ queries are given respectively. Each query consists of two integers $s$ and $t$ separated by a space character.

Output

For each query, print "yes" if $t$ is reachable from $s$ through the social network, "no" otherwise.

Constraints

$2 \leq n \leq 100,000$

$0 \leq m \leq 100,000$

$1 \leq q \leq 10,000$

Sample Input

10 9
0 1
0 2
3 4
5 7
5 6
6 7
6 8
7 8
8 9
3
0 1
5 9
1 3

Sample Output

yes
yes
no

Solution in C# (judge verdict: Accepted)



using System;
using System.Linq;
using System.Collections.Generic;

class Program {

    const int MAX = 100001;
    const int wht = 0;
    const int gry = 1;
    const int blk = 2;
    static int[] stt = new int[MAX];
    static int[] grp = new int[MAX];

    static List<List<int>> g = new List<List<int>>();

    static void Main(string[] args) {

        grp = Enumerable.Repeat(-1, MAX).ToArray();
        var inp = Console.ReadLine().Split(' ').Select(z => int.Parse(z)).ToArray();

        for (int i = 0; i < inp[0] + 1; i++) {
            g.Add(new List<int>());
        }

        for (int i = 0; i < inp[1]; i++) {
            var a = Console.ReadLine().Split(' ').Select(z => int.Parse(z)).ToArray();
            g[a[0]].Add(a[1]);
            g[a[1]].Add(a[0]);
        }

        for (int i = 0; i < inp[0]; i++) {
            bfs(i);
        }

        var q = int.Parse(Console.ReadLine());
        for (int i = 0; i < q; i++) {
            var a = Console.ReadLine().Split(' ').Select(z => int.Parse(z)).ToArray();
            string s = grp[a[0]] == grp[a[1]] ? "yes" : "no";
            Console.WriteLine(s);
        }

    }


    static void bfs(int v) {

        var q = new Queue<int>();
        q.Enqueue(v);
        grp[v] = grp[v] == -1 ? v : grp[v];

        while (q.Count > 0) {

            var u = q.Dequeue();
            for (int i = 0; i < g[u].Count; i++) {
                int c = g[u][i];
                if (stt[c] != blk) {
                    q.Enqueue(c);
                    stt[c] = gry;
                    grp[c] = grp[c] == -1 ? v : grp[c];
                }
            }

            stt[u] = blk;
        }
    }
}