728x90
나의 풀이
def find(parent, x):
if parent[x] != x:
parent[x] = find(parent, parent[x])
return parent[x]
def union(parent, x, y):
x, y = find(parent, x), find(parent, y)
if x > y:
parent[x] = y
else:
parent[y] = x
def solution(n, costs):
answer = 0
parent = [i for i in range(n)]
costs.sort(key=lambda edge: edge[2])
for i in range(len(costs)):
a, b, cost = costs[i]
if find(parent, a) != find(parent, b):
union(parent, a, b)
answer += cost
return answer
heapq를 사용한 풀이
import heapq as hq
def solution(n, costs):
answer = 0
from_to = list(list() for _ in range(n))
visited = [False] * n
priority = []
for a, b, cost in costs:
from_to[a].append((b, cost))
from_to[b].append((a, cost))
hq.heappush(priority, (0, 0))
while False in visited:
cost, start = hq.heappop(priority)
if visited[start]: continue
visited[start] = True
answer += cost
for end, cost in from_to[start]:
if visited[end] : continue
else:
hq.heappush(priority, (cost, end))
return answer
반응형
'Coding Test > Programmers' 카테고리의 다른 글
[프로그래머스/파이썬] N으로 표현 (0) | 2022.06.07 |
---|---|
[프로그래머스/파이썬] 단속카메라 (0) | 2022.06.07 |
[프로그래머스/파이썬] 구명보트 (0) | 2022.06.07 |
[프로그래머스/파이썬] 큰 수 만들기 (0) | 2022.06.07 |
[프로그래머스/파이썬] 조이스틱 (0) | 2022.06.06 |