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: class UnionFind:
    def __init__(self, n: int):
        self.nodes = n
        self.parents = [-1] * n
        self.rank = [0] * n

    # retrun the root of element x
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    # unite the group include element x and group include element y
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            self.parents[y] += self.parents[x]
            self.parents[x] = y
        else:
            self.parents[x] += self.parents[y]
            self.parents[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # get size of the gourp which element x belongs
    def get_size(self, x):
        return -self.parents[self.find(x)]

    # check if element x and element y is same group
    def same(self, x, y):
        return self.find(x) == self.find(y)


n, m = [int(i) for i in input().split()]
union = UnionFind(n)
for _ in range(m):
    s, t = [int(i) for i in input().split()]
    union.unite(s, t)

q = int(input())
for _ in range(q):
    s, t = [int(i) for i in input().split()]
    if union.same(s, t):
        print("yes")
    else:
        print("no")

Python: #coding:utf-8
n, r = map(int,input().split())
Q = []
M = [[] for j in range(n)]
for i in range(r):
    i,j = map(int,input().split())
    M[i].append(j)
    M[j].append(i)


def search(person, target):
    data = M[person]
    for per in data:
        if per ==  target:
            global yes
            yes = 1
            return
        if color[per] == "white":
            color[per] = "gray"
            search(per, target)
    color[person] = "black"

num = int(input())
for i in range(num):
    yes = 0
    color = ["white" for j in range(n)]
    person, target = map(int,input().split())
    search(person, target)
    if yes == 0:
        print("no")
    else:
        print("yes")

Python: #!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys


def assign_color():
    _id = 1
    for m in range(vertices_num):
        if vertices_status_list[m] == -1:
            graph_dfs(m, _id)
            _id += 1
    return None


def graph_dfs(vertex, color):
    vertices_stack = list()
    vertices_stack.append(vertex)
    vertices_status_list[vertex] = color
    while vertices_stack:
        current_vertex = vertices_stack[-1]
        vertices_stack.pop()
        for v in adj_list[current_vertex]:
            if vertices_status_list[v] == -1:
                vertices_status_list[v] = color
                vertices_stack.append(v)
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num, relation_num = map(int, _input[0].split())

    relation_info = _input[1:relation_num + 1]

    question_num = int(_input[relation_num + 1])
    question_list = _input[relation_num + 2:]

    adj_list = [[] for _ in range(vertices_num)]
    vertices_status_list = [-1] * vertices_num

    for relation in relation_info:
        key, value = map(int, relation.split())
        adj_list[key].append(value)
        adj_list[value].append(key)

    assign_color()

    # print(adj_list)
    for question in question_list:
        start, target = map(int, question.split())
        if vertices_status_list[start] == vertices_status_list[target]:
            print("yes")
        else:
            print("no")

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')

N,M=MAP()
nodes=[[] for i in range(N)]
for i in range(M):
    s,t=MAP()
    nodes[s].append(t)
    nodes[t].append(s)

group=[-1]*N
def rec(u, root):
    if group[u]!=-1:
        return
    group[u]=root
    for v in nodes[u]:
        rec(v, root)

for i in range(N):
    rec(i, i)

Q=INT()
for _ in range(Q):
    s,t=MAP()
    if group[s]==group[t]:
        print('yes')
    else:
        print('no')

Python: import sys

def srch(i, end, l, Dst, Lng):
    if Lng[i] != -1 and Lng[i] < l:
        return
    Lng[i] = l
    if i == end:
        return
    if Dst[i] is not None and len(Dst[i]) > 0:
        for c in Dst[i]:
            srch(c, end, l+1, Dst, Lng)

def main():
    istr = sys.stdin.read()
    ilist = []
    for i in istr.splitlines():
        ilist.append(list(map(int,i.split())))
    #print(ilist)
    unum, fnum = ilist[0]

    Dst = [[] for i in range(unum)]
    fnum += 1
    for n in range(1, fnum):
        uid, fid = ilist[n]
        Dst[uid].append(fid)
        Dst[fid].append(uid)
    
    qnum = ilist[fnum][0]
    fnum += 1
    #print("fnum={} qnum={}".format(fnum,qnum))
    for q in range(fnum, (fnum + qnum)):
        id1, id2 = ilist[q]
        Lng = [-1] * (fnum)
        #print("[{}] id1={:2} id2={:2} Dst:{} Lng:{}".format(q,id1, id2, Dst, Lng))
        srch(id1, id2, 0, Dst, Lng)
        if Lng[id2] != -1:
            print("yes")
        else:
            print("no")

if __name__ == '__main__':
    main()

Python: from collections import deque

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

V =[deque([]) for _ in range(n)]
color = [0 for _ in range(n)]

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

friend = 1

def dfs(u,f):
    global color
    color[u] = f
    stack = []
    stack.append(u)
    while len(stack) != 0:
        now = stack[-1]
        # print(now,V,color)
        if len(V[now]) != 0:
            nb = V[now].popleft()
            if color[nb] == 0:
                stack.append(nb)
                color[nb] = f
        else :
            stack.pop()

# print("")

for i in range(n):
    if color[i]==0:
        dfs(i,friend)
        friend += 1

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