Go: package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)

func nextString() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

func newGraph(nNodes int) *Graph {
	g := Graph{}
	g.nodes = make([]*GraphNode, nNodes)
	for iNode := 0; iNode < len(g.nodes); iNode++ {
		g.nodes[iNode] = &GraphNode{}
		g.nodes[iNode].key = GraphNodeKey(iNode)
	}
	return &g
}

var infty = 1000000000

type GraphNodeKey int

// GraphNode is a node for undirected graph
type GraphNode struct {
	key       GraphNodeKey
	adjacents []*GraphNode
	visited   bool
	d, f      int
	parent    *GraphNode
	cc        int
}

func (g *Graph) setAdjacent(l, r GraphNodeKey) {
	g.nodes[l].adjacents = append(g.nodes[l].adjacents, g.nodes[r])
}

// Graph is a undirected graph
type Graph struct {
	nodes []*GraphNode
}

func (g *Graph) initialize() {
	for iNode := 0; iNode < len(g.nodes); iNode++ {
		g.nodes[iNode].visited = false
		g.nodes[iNode].d = infty
		g.nodes[iNode].f = infty
		g.nodes[iNode].parent = nil
		g.nodes[iNode].cc = -1 // 22.3-12
	}
}

type QueueEntry struct {
	node *GraphNode
	next *QueueEntry
}

type Queue struct {
	head, tail *QueueEntry
}

func (q *Queue) enqueue(node *GraphNode) {
	entry := QueueEntry{}
	entry.node = node

	if q.tail == nil {
		q.head = &entry
		q.tail = &entry
		return
	}

	q.tail.next = &entry
	q.tail = q.tail.next
}

func (q *Queue) dequeue() *QueueEntry {
	if q.head == nil {
		return nil
	}
	poped := q.head
	q.head = q.head.next
	if q.head == nil {
		q.tail = nil
	}
	return poped
}

func (q *Queue) isEmpty() bool {
	return q.head == nil
}

var time = 0

func fillDistancesByDepthFirstSearch(g *Graph) {
	g.initialize()
	time = 0
	cc := 0

	for _, u := range g.nodes {
		if !u.visited {
			dfsVisit(g, u, cc)
			cc++
		}
	}
}

func dfsVisit(g *Graph, u *GraphNode, cc int) {
	time++
	u.d = time
	u.cc = cc

	u.visited = true
	for _, v := range u.adjacents {
		if !v.visited {
			v.parent = u
			dfsVisit(g, v, cc)
		}
	}
	time++
	u.f = time
}

func main() {
	scanner.Split(bufio.ScanWords)

	nUsers := nextInt()
	nEdges := nextInt()
	graph := newGraph(nUsers)
	for iEdge := 0; iEdge < nEdges; iEdge++ {
		l := GraphNodeKey(nextInt())
		r := GraphNodeKey(nextInt())
		graph.setAdjacent(l, r)
		graph.setAdjacent(r, l)
	}

	fillDistancesByDepthFirstSearch(graph)

	nQueries := nextInt()
	for iQuery := 0; iQuery < nQueries; iQuery++ {
		l := GraphNodeKey(nextInt())
		r := GraphNodeKey(nextInt())

		// fmt.Println(graph.nodes[l].d, graph.nodes[r].d, graph.nodes[r].f, graph.nodes[l].f)
		if graph.nodes[l].cc == graph.nodes[r].cc {
			fmt.Println("yes")
		} else {
			fmt.Println("no")
		}
	}
}

Python: n, m = map(int, input().split())
rootList = [-1 for i in range(n)]
 
def getRoot(x):
    if rootList[x] < 0:
        rootList[x] = x
        return x
    return getRoot(rootList[x])
 
 
def setSameRoot(x, y):
    x = getRoot(x)
    y = getRoot(y)
    if x != y:
        rootList[x], rootList[y] = min(x, y), min(x, y)
 
for i in range(m):
    s, t = map(int, input().split())
    setSameRoot(s, t)
q = int(input())
for i in range(q):
    s, t = map(int, input().split())
    print("yes" if getRoot(s) == getRoot(t) != -1 else "no")

Python: class UnionFind:
    def __init__(self,n):
        self.n = n
        self.p = [i for i in range(n)]
        self.rank = [0]*n

    def same(self,x,y):
        return self.root(x)==self.root(y)

    def root(self,x):
        if x!=self.p[x]:self.p[x] = self.root(self.p[x])
        return self.p[x]

    def unite(self,x,y):
        x = self.root(x)
        y = self.root(y)
        if self.rank[y]<self.rank[x]:
            self.p[y] = x
        else:
            self.p[x] = y
            if self.rank[y]==self.rank[x]:
                self.rank[y]+=1

def main():
    n,m = map(int,input().split())
    UF = UnionFind(n)
    for _ in range(m):
        a,b = map(int,input().split())
        UF.unite(a,b)
    q = int(input())
    for _ in range(q):
        a,b = map(int,input().split())
        if UF.same(a,b):print ('yes')
        else           :print ('no')


if __name__ == '__main__':
    main()

Python: from collections import deque


user_num,rer_num=map(int,input().split())
graph=[[] for loop in range(user_num)]

for loop in range(rer_num):
    user1,user2=map(int,input().split())
    graph[user1].append(user2)
    graph[user2].append(user1)

#group[user1]はuser1が属するグループ.同じグループに属するuser同士は互いに到達可能
group=[-1]*user_num

que=deque([])
que.append(0)
tmp_group=0
for user in range(user_num):
    if(group[user]==-1):
        que.append(user)
        group[user]=tmp_group
        while(1):
            user1=que.popleft()
            for user2 in graph[user1]:
                if(group[user2]==-1):
                    que.append(user2)
                    group[user2]=tmp_group
            if(len(que)==0):
                tmp_group+=1
                break

for loop in range(int(input())):
    user1,user2=map(int,input().split())
    if(group[user1]==group[user2]):
        print("yes")
    else:
        print("no")

Python: from collections import defaultdict
user_num, conn_num = (int(n) for n in input().split(" "))
conn = defaultdict(list)
for _ in range(conn_num):
    i, j = (int(n) for n in input().split(" "))
    conn[i].append(j)
    conn[j].append(i)
find = [-1 * n - 1 for n in range(user_num)]
query = int(input())
for q_num in range(query):
    one, theother = (int(n) for n in input().split(" "))
    if find[one] != find[theother] and find[one] < 0:
        queue = [one]
        find[one] = q_num
        while queue:
            new_queue = []
            for q in queue:
                for c in conn[q]:
                    if find[c] < 0:
                        new_queue.append(c)
                        find[c] = q_num
            queue = new_queue
    if find[one] == find[theother]:
        print("yes")
    else:
        print("no")

Python: from collections import deque


def CC():
    id=0
    color=["white" for i in range(n)]
    for j in range(n):
        if color[j]=="white":
            color[j]="gray"
            queue=deque([j])

            while len(queue)!=0:
                u=queue.popleft()
                for i in M[u]:
                    if color[i]=="white":
                        color[i]="gray"
                        queue.append(i)
                color[u]=str(id)
            id +=1

    return color


n,m=map(int,input().split())
M=[[] for i in range(n)]
for i in range(m):
    p,q=map(int,input().split())
    M[p].append(q)
    M[q].append(p)

color=CC()

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

Python: # Connected Components
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)

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) and (color[t] is not None)) and (color[s] == color[t]):
        # s,tも友達がいて、かつ同じグループだったら
        print('yes')
    else:
        print('no')