Skip to content

Commit dcbe9ca

Browse files
learntosurfMingguriguri
authored andcommitted
[BOJ] #1717.집합의 표현 / 골드4 / 60(X_
1 parent a239c79 commit dcbe9ca

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import sys
2+
input = sys.stdin.readline
3+
sys.setrecursionlimit(10**6)
4+
5+
n, m = map(int, input().split())
6+
parent = [i for i in range(n + 1)]
7+
rank = [0] * (n + 1) # 트리 깊이 관리
8+
result = []
9+
10+
def find(x):
11+
if parent[x] != x:
12+
parent[x] = find(parent[x]) # 경로 압축
13+
return parent[x]
14+
15+
def union(x, y):
16+
root_x = find(x)
17+
root_y = find(y)
18+
19+
if root_x != root_y:
20+
if rank[root_x] > rank[root_y]: # 더 랭크가 높은 루트로 합침
21+
parent[root_y] = root_x
22+
elif rank[root_x] < rank[root_y]:
23+
parent[root_x] = root_y
24+
else:
25+
parent[root_y] = root_x
26+
rank[root_x] += 1 # 같은 랭크면 한쪽의 랭크 증가
27+
28+
29+
for _ in range(m):
30+
op, a, b = map(int, input().split())
31+
32+
if op == 0: # 합집합 연산
33+
union(a, b)
34+
35+
elif op == 1: # 같은 집합 여부 확인
36+
if find(a) == find(b):
37+
result.append("YES")
38+
else:
39+
result.append("NO")
40+
41+
sys.stdout.write("\n".join(result) + "\n")

0 commit comments

Comments
 (0)