[백준] 1753번 : 최단경로 [파이썬]

[백준] 1753번 : 최단경로 [파이썬]

import heapq

import sys

input = sys . stdin . readline

INF = int ( 1e9 ) # 무한을 의미

v , e = map ( int , input (). split ()) # 정점과 간선의 개수 입력

start = int ( input ()) # 시작노드 정보

graph =[[] for _ in range ( v + 1 )] # 연결정보를 담을 graph

distance =[ INF ]*( v + 1 )

for _ in range ( e ):

a , b , c = map ( int , input (). split ()) # a에서 b로가는 비용이 c

graph [ a ]. append (( b , c ))

def dij ( start ):

q =[]

heapq . heappush ( q ,( 0 , start )) # 자신에게 가는 거리는 0

distance [ start ]= 0

while q :

dist , now = heapq . heappop ( q )

if distance [ now ]< dist :

continue

for i in graph [ now ]:

cost = dist + i [ 1 ]

if cost < distance [ i [ 0 ]]:

distance [ i [ 0 ]]= cost

heapq . heappush ( q ,( cost , i [ 0 ]))

dij ( start )

for i in range ( 1 , len ( distance )):

if distance [ i ]== INF :

print ( 'INF' )

else :

from http://20210916start.tistory.com/55 by ccl(A) rewrite - 2021-09-23 04:26:53