File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ # 특정 원소가 속한 집합을 찾기
2+ def find_parent (parent , x ):
3+ # 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
4+ if parent [x ] != x :
5+ parent [x ] = find_parent (parent , parent [x ])
6+ return parent [x ]
7+
8+ # 두 원소가 속한 집합을 합치기
9+ def union_parent (parent , a , b ):
10+ a = find_parent (parent , a )
11+ b = find_parent (parent , b )
12+ if a < b :
13+ parent [b ] = a
14+ else :
15+ parent [a ] = b
16+
17+ # 노드의 개수와 간선(Union 연산)의 개수 입력 받기
18+ v , e = map (int , input ().split ())
19+ parent = {}
20+
21+ # 모든 간선을 담을 리스트와, 최종 비용을 담을 변수
22+ edges = []
23+ result = 0
24+
25+ # 부모 테이블상에서, 부모를 자기 자신으로 초기화
26+ for i in range (1 , v + 1 ):
27+ parent [i ] = i
28+
29+ # 모든 간선에 대한 정보를 입력 받기
30+ for _ in range (e ):
31+ a , b , cost = map (int , input ().split ())
32+ # 비용순으로 정렬하기 위해서 튜플의 첫 번째 원소를 비용으로 설정
33+ edges .append ((cost , a , b ))
34+
35+ # 간선을 비용순으로 정렬
36+ edges .sort ()
37+ last = 0
38+
39+ # 간선을 하나씩 확인하며
40+ for edge in edges :
41+ cost , a , b = edge
42+ # 사이클이 발생하지 않는 경우에만 집합에 포함
43+ if find_parent (parent , a ) != find_parent (parent , b ):
44+ union_parent (parent , a , b )
45+ result += cost
46+ last = cost
47+
48+ print (result - last )
You can’t perform that action at this time.
0 commit comments