Go: // AOJ ALDS1_11_D: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_D

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"os"
	"strconv"
)

var nocolor = -1

type graph struct {
	graph  [][]int
	colors []int
}

func nextInt(sc *bufio.Scanner) int {
	sc.Scan()
	v, _ := strconv.Atoi(sc.Text())
	return v
}

func newGraph(nodeNum int) *graph {
	colors := make([]int, nodeNum)
	g := make([][]int, nodeNum)
	for i := 0; i < nodeNum; i++ {
		g[i] = []int{}
		colors[i] = nocolor
	}

	return &graph{g, colors}
}

func constructGraph(sc *bufio.Scanner) *graph {
	usersNum := nextInt(sc)
	linkNum := nextInt(sc)

	g := newGraph(usersNum)
	for i := 0; i < linkNum; i++ {
		u := nextInt(sc) // node
		l := nextInt(sc) // link node
		// edge each other
		g.graph[u] = append(g.graph[u], l)
		g.graph[l] = append(g.graph[l], u)
	}
	return g
}

func (g *graph) dfs(r, color int) {
	g.colors[r] = color

	stack := list.New()
	stack.PushFront(r)

	for stack.Len() > 0 {
		v := stack.Remove(stack.Front()).(int)
		for _, u := range g.graph[v] {
			if g.colors[u] == nocolor {
				g.colors[u] = color
				stack.PushFront(u)
			}
		}
	}
}

func (g *graph) assignColor() {
	color := 1
	for u := 0; u < len(g.graph); u++ {
		if g.colors[u] == nocolor {
			g.dfs(u, color)
			color++
		}
	}
}

func (g *graph) isLink(s, t int) bool {
	return g.colors[s] == g.colors[t]
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	// construct graph and friendly colors
	g := constructGraph(sc)
	g.assignColor()

	// judge link
	q := nextInt(sc)
	for i := 0; i < q; i++ {
		s := nextInt(sc)
		t := nextInt(sc)

		if g.isLink(s, t) {
			fmt.Println("yes")
		} else {
			fmt.Println("no")
		}
	}
}

Python: import sys
from collections import deque, defaultdict

sys.setrecursionlimit(10**7)

n, m = map(int, input().split())

G = defaultdict(lambda: deque())
color = [-1]*n

for _ in range(m):
    s, t = map(int, input().split())
    G[s].append(t)
    G[t].append(s)

def dfs(node, co):
    if color[node] != -1:
        return

    color[node] = co

    for n in G[node]:
        dfs(n, co)
        

c = 1
for node in G.keys():
    dfs(node, c)
    c += 1


q = int(input())
for _ in range(q):
    s, t = map(int, input().split())
    if color[s] != -1 and color[t] != -1 and color[s] == color[t]:
        print('yes')
    else:
        print('no')

Python: n = list(map(int,input().split()))
cn = [i for i in range(n[0])]
for i in range(n[1]):
    a = list(map(int,input().split()))
    if cn[a[0]] != cn[a[1]]:
        for j in range(n[0]):
            if cn[j] == cn[a[1]]:
                cn[j] = cn[a[0]]


q = int(input())
for i in range(q):
    a = list(map(int,input().split()))
    if cn[a[0]] == cn[a[1]]: print("yes")
    else: print("no")

Python: from collections import deque


n = 0
m = 0
M = None
color = None


def main():
    global n, m, M, color
    n, m = map(int, input().split(' '))

    M = [[] for _ in range(n)]
    color = [-1 for _ in range(n)]

    for _ in range(m):
        a, b = map(int, input().split(' '))
        M[a].append(b)
        M[b].append(a)

    num = 1
    for u in range(n):
        if color[u] == -1:
            dfs(u, num)
            num += 1

    k = int(input())
    for _ in range(k):
        a, b = map(int, input().split(' '))
        if color[a] == color[b]:
            print('yes')
        else:
            print('no')


def dfs(r, c):
    stack = deque()
    stack.append(r)
    color[r] = c
    while len(stack) > 0:
        u = stack.pop()
        for i in range(len(M[u])):
            v = M[u][i]
            if color[v] == -1:
                color[v] = c
                stack.append(v)


if __name__ == '__main__':
    main()

Python: n, m = map(int, raw_input().split())
G = [[0 for i in range(n)] for j in range(n)]

for i in range(m):
    s, t = map(int, raw_input().split())
    G[s][t] = 1
    G[t][s] = 1

for i in range(n):
    for j in range(n):
        for k in range(n):
            if G[j][k] == 1:
                for l in range(k+1, n):
                    if G[k][l] == 1:
                        G[j][l] = 1
                        G[l][j] = 1

q = int(raw_input())
ans = ["no" for i in range(q)]
for i in range(q):
    s, t = map(int, raw_input().split())
    if G[s][t] == 1:
        ans[i] = "yes"
for i in range(q):
    print(ans[i])

Python: # -*- coding: utf-8 -*-

import sys

sys.setrecursionlimit(10 ** 9)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
INF=float('inf')

# Union-Find木
class UnionFind:
    def __init__(self, n):
        self.n = n
        # 親要素のノード番号を格納。par[x] == xの時そのノードは根
        # 1-indexedのままでOK、その場合は[0]は未使用
        self.par = [i for i in range(n+1)]
        # 木の高さを格納する（初期状態では0）
        self.rank = [0] * (n+1)
        # あるノードを根とする集合に属するノード数
        self.size = [1] * (n+1)
        # あるノードを根とする集合が木かどうか
        self.tree = [True] * (n+1)

    # 根の検索(グループ番号と言えなくもない)
    def find(self, x):
        # 根ならその番号を返す
        if self.par[x] == x:
            return x
        else:
            # 走査していく過程で親を書き換える
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        # 根を探す
        x = self.find(x)
        y = self.find(y)

        # 木かどうかの判定用
        if x == y:
            self.tree[x] = False
            return
        if not self.tree[x] or not self.tree[y]:
            self.tree[x] = self.tree[y] = False

        # 木の高さを比較し、低いほうから高いほうに辺を張る
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
            # 木の高さが同じなら片方を1増やす
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same(self, x, y):
        return self.find(x) == self.find(y)

    # あるノードの属する集合のノード数
    def get_size(self, x):
        return self.size[self.find(x)]

    # 木かどうかの判定
    def is_tree(self, x):
        return self.tree[self.find(x)]

    # 集合の数
    def len(self):
        res = set()
        for i in range(self.n+1):
            res.add(self.find(i))
        # グループ0の分を引いて返却
        return len(res) - 1

N,M=MAP()
uf=UnionFind(N)
for i in range(M):
    s,t=MAP()
    uf.union(s, t)

Q=INT()
for _ in range(Q):
    s,t=MAP()
    if uf.same(s, t):
        print('yes')
    else:
        print('no')

C++: #include<iostream>
#include<vector>
#include<stack>
using namespace std;
static const int MAX=100000;
static const int NIL=-1;

int n;
vector<int>G[MAX];
int color[MAX];

void dfs(int r,int c){
  stack<int> S;
  S.push(r); 
  color[r]=c;
  while(!S.empty()){
    int u=S.top();
    S.pop();
    for(int i=0;i<G[u].size();i++){
      int v=G[u][i];
      if(color[v]==NIL){
	color[v]=c;
	S.push(v);
      }
    }
  }
}
int main(){
  int s,t,m,q;
  cin>>n>>m;


for(int i=0;i<m;i++){
  cin>>s>>t;
  G[s].push_back(t);
  G[t].push_back(s);
 }

int id=1;
for(int i=0;i<n;i++){
  color[i]=NIL;
 }

for(int u=0;u<n;u++){
  if(color[u]==NIL)
    dfs(u,id++);
 }

cin>>q;

for(int i=0;i<q;i++){
  cin>>s>>t;
  if(color[s]==color[t]){
    cout<<"yes"<<endl;
  }
  else{
    cout<<"no"<<endl;
  }
 }
return 0;
}