- Notifications
You must be signed in to change notification settings - Fork 846
/
Copy path7.py
35 lines (31 loc) · 1.01 KB
/
7.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 특정 원소가 속한 집합을 찾기
deffind_parent(parent, x):
# 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
ifparent[x] !=x:
parent[x] =find_parent(parent, parent[x])
returnparent[x]
# 두 원소가 속한 집합을 합치기
defunion_parent(parent, a, b):
a=find_parent(parent, a)
b=find_parent(parent, b)
ifa<b:
parent[b] =a
else:
parent[a] =b
n, m=map(int, input().split())
parent= [0] * (n+1) # 부모 테이블 초기화
# 부모 테이블상에서, 부모를 자기 자신으로 초기화
foriinrange(0, n+1):
parent[i] =i
# 각 연산을 하나씩 확인
foriinrange(m):
oper, a, b=map(int, input().split())
# 합치합(Union) 연산인 경우
ifoper==0:
union_parent(parent, a, b)
# 찾기(Find) 연산인 경우
elifoper==1:
iffind_parent(parent, a) ==find_parent(parent, b):
print('YES')
else:
print('NO')