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: # https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/11/ALDS1_11_D

from collections import defaultdict
import sys
sys.setrecursionlimit(1 << 25)  # 再起上限引き上げ

G = defaultdict(lambda: [])

# load data
N, M = list(map(int, input().split()))
color = {key: None for key in range(N)}  # 色というかグループ #intで表す #Noneは未訪問を示す
# graphをdefault dictで保持することにする。
for _ in range(M):
    s, t = list(map(int, input().split()))
    G[s].append(t)
    G[t].append(s)

# 離接リストをもとに、たどり着ける友達関係をグループ化する #(union findが使える気もするけどここではDFSで領域を探索していく)


def dfs(node: int, co: int):
    # 終了条件 #すでに訪問済みなら訪問しない
    if color[node] is not None:
        return
    # 処理
    color[node] = co
    # 探索
    for n in G[node]:
        dfs(n, co)
    return


# すべてのnodeを開始点としてdfsで領域わけしてみる
c = 1
for node in G.keys():
    dfs(node, c)  # 訪問済みだったら色を塗り替えないというないようはdfs関数内の処理で吸収できる
    c += 1


# 問題に回答していく
Q = int(input())
for _ in range(Q):
    s, t = list(map(int, input().split()))
    if ((color[s] is not None) or (color[t] is not None)) and (color[s] == color[t]):
        # s,tも友達がいて、かつ同じグループだったら
        print('yes')
    else:
        print('no')

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+1):
    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

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: import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def paint_col(adj, cols, i, col):
    nxt = deque([i])

    while nxt:
        u = nxt.popleft()
        cols[u] = col
        for child in adj[u]:
            if cols[child] == 0:
                nxt.append(child)

def solve():
    n, m = map(int, input().split())
    adj = [[] for i in range(n)]

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

    cols = [0] * n
    col = 1

    for i in range(n):
        if cols[i] == 0:
            paint_col(adj, cols, i, col)
            col += 1

    q = int(input())

    for i in range(q):
        s, t = map(int, input().split())

        if cols[s] == cols[t]:
            ans = 'yes'
        else:
            ans = 'no'

        print(ans)

if __name__ == '__main__':
    solve()

Python: import sys
readline = sys.stdin.readline
def MAIN():
    n, m = map(int, input().split())
    li = [i for i in range(n)]
    def f(a):
        if li[a] == a:
            return a
        li[a] = f(li[a])
        return li[a]
    def f2(a, b):
        if li[a] == a:
            li[a] = b
            return
        f2(li[a], b)
        li[a] = b
    for _ in range(m):
        x, y = map(int, readline().split())
        if f(x) > f(y):
            f2(x, li[y])
        elif f(x) < f(y):
            f2(y, li[x])
    for _ in range(int(input())):
        x, y = map(int, readline().split())
        print("yes" if f(a) == f(b) else "no")
MAIN()

Python: def bfs(s, t):
  q = [s]
  while len(q) > 0:
    v = q.pop(0)
    if v == t: return True
    if len(G[v]) > 0:
      q.extend(sorted(G[v]))
      G[v] = []
  return False

u, n = map(int, input().split())
G = [[] for _ in range(u)]
for _ in range(n):
  a, b = map(int, input().split())
  if b not in G[a]: G[a].append(b)
  if a not in G[b]: G[b].append(a)

q = int(input())
for _ in range(q):
  s, t = map(int, input().split())
  if bfs(s, t):
    print("yes")
  else:
    print("no")

Python: from collections import deque

def dfs(r: int, c: int) -> None:
	S = deque()
	S.append(r)
	color[r] = c
	while S:
		u = S.pop()
		for v in G[u]:
			if color[v] == None:
				color[v] = c
				S.append(v)

def assignColor():
	id: int = 1
	for u in range(n):
		if color[u] == None:
			dfs(u, id)
			id += 1


if __name__ == "__main__":
	n, m = map(int, input().split())
	G = [[] for _ in range(n)]
	for _ in range(m):
		u, v = map(int, input().split())
		G[u].append(v)
		G[v].append(u)
	color = [None for _ in range(n)]
	assignColor()
	q = int(input())
	for _ in range(q):
		u, v = map(int, input().split())
		if color[u] == color[v]:
			print("yes")
		else:
			print("no")

Python: import sys
import copy
from collections import deque
sys.setrecursionlimit(20000)
N,relation=input().split()
N,relation=int(N),int(relation)
g = [set() for i in range(N)]

def BFS(a,b):
    bfs = deque([a])
    grp={a:None}
    grp2={a}
    while bfs:
        i=bfs.popleft()
        for j in g[i]:
            if j not in grp2:
                grp[j]=a
                grp2.add(j)
                bfs.append(j)
    return grp,grp2


for i in range(relation):
    kari=[]
    j,k=list(map(int,input().split()))
    g[j].add(k)
    g[k].add(j)
group=[]
tansaku=int(input())
for i in range(tansaku):
    a,b=list(map(int,input().split()))
    for k in range(len(group)):
        if a in group[k] and b in group[k]:
            print("yes")
            break
        elif a in group[k]:
            print("no")
            break
    else:
        grp,grp2=(BFS(a,b))
        grp=set(grp.keys())
        if b in grp:
            print("yes")
        else:print("no")
        group.append(grp)