λ§žμ™œν‹€

[python] λ°±μ€€ - 11085. ꡰ사 이동 λ³Έλ¬Έ

Algorithm Problem/Python

[python] λ°±μ€€ - 11085. ꡰ사 이동

deo2kim 2021. 9. 10. 21:51
λ°˜μ‘ν˜•

πŸ€”λ¬Έμ œ ν•΄κ²°

  • 크루슀칼
  1. Cμ—μ„œ 좜발! 갈 수 μžˆλŠ” 곳을 μ°Ύμ•„μ„œ μš°μ„ μˆœμœ„ 큐에 λ„£λŠ”λ‹€.
  2. μš°μ„ μˆœμœ„ νμ—μ„œ 넓이가 κ°€μž₯ 넓은 녀석을 λ½‘λŠ”λ‹€.
  3. κ±°κΈ°μ„œ 또 갈 수 μžˆλŠ” 곳을 μ°Ύμ•„μ„œ 큐에 λ„£λŠ”λ‹€. (단, 재방문 X)
  4. Vλ₯Ό λ§Œλ‚˜λ©΄ 끝!

λ…Έλ“œλ₯Ό μ΄λ™ν•˜λŠ” λ™μ•ˆ μ΅œμ†Œκ°’μ„ 계속 κ°±μ‹ ν•΄μ€€λ‹€. (닡을 μ°Ύμ•„μ•Όν•˜λ―€λ‘œ)

 

πŸ’»μ†ŒμŠ€ μ½”λ“œ

import sys
from collections import defaultdict
import heapq

input = sys.stdin.readline

P, W = map(int, input().split())  # P개의 지점, W개의 κΈΈ
C, V = map(int, input().split())  # C λ°±μ€€μˆ˜λ„, V νλΈŒμˆ˜λ„

# μΈμ ‘λ…Έλ“œ λ§Œλ“€κΈ°
nodes = [input() for _ in range(W)]
adj = defaultdict(list)
for node in nodes:
    a, b, c = map(int, node.split())
    adj[a].append([b, c])
    adj[b].append([a, c])

# μš°μ„ μˆœμœ„ 큐
visited = [0] * P
pq = []
heapq.heappush(pq, [-1e9, C])
answer = 1e9 # μ΅œμ†Œκ°’ μ°ΎκΈ°

while pq:
    cur_cost, cur_node = heapq.heappop(pq)
    cur_cost *= -1

    if visited[cur_node]:
        continue
    visited[cur_node] = 1

    answer = min(answer, cur_cost)
    if cur_node == V:
        print(answer)
        break

    for next_node, next_cost in adj[cur_node]:
        heapq.heappush(pq, [-next_cost, next_node])

 

πŸ“•λ¬Έμ œ 확인

좜처: BACKJOON ONLINE JUDGE

 

 

λ°˜μ‘ν˜•