Skip to content

Commit bfd963e

Browse files
committed
[BOJ] #5107. 마니또 / 실버1 / 80분 / 실패
1 parent 35d4a63 commit bfd963e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import sys
2+
3+
input = sys.stdin.readline
4+
5+
6+
# Find 연산(같은 집합에 속하는지 확인하기 위한 함수)
7+
def find(a):
8+
if a != parent[a]:
9+
parent[a] = find(parent[a]) # 경로 압축
10+
return parent[a]
11+
12+
13+
# Union 연산(두 집합을 합치기 위한 함수)
14+
def union(a, b):
15+
p_a = find(a)
16+
p_b = find(b)
17+
18+
if p_a > p_b: # 값이 더 작은 쪽을 부모로 설정
19+
parent[p_a] = p_b
20+
else:
21+
parent[p_b] = p_a
22+
23+
24+
tc_num = 0 # 테스트케이스 개수
25+
while True:
26+
N = int(input())
27+
parent = [i for i in range(N + 1)] # 초기: 각 원소가 자기 자신을 부모로 가짐
28+
manito = {}
29+
tc_num += 1 # 테스트케이스 업데이트
30+
31+
if N == 0: # 입력 종료
32+
break
33+
34+
for _ in range(N):
35+
from_p, to_p = input().split()
36+
# manito에 번호 부여
37+
if from_p not in manito:
38+
manito[from_p] = len(manito) + 1
39+
if to_p not in manito:
40+
manito[to_p] = len(manito) + 1
41+
# 합집합 연산
42+
union(parent[manito[from_p]], parent[manito[to_p]])
43+
44+
parent = set(parent)
45+
46+
print(tc_num, len(parent) - 1) # 0이 포함되어 있으므로 1 빼주어야 함

0 commit comments

Comments
 (0)