File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 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 빼주어야 함
You can’t perform that action at this time.
0 commit comments