💡문제접근
- 개선된 다익스트라 알고리즘 (시간 복잡도 :
O(E log V)
)
💡코드(메모리 : 58532KB, 시간 : 352ms)
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)
N = int(input())
M = int(input())
graph = [[] for _ in range(N+1)]
distance = [INF] * (N+1)
for _ in range(M):
a, b, c = map(int, input().strip().split())
graph[a].append([b, c])
start, end = map(int, input().strip().split())
def dijkstra(start):
q = []
heapq.heappush(q, (0, start))
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]))
return distance
result = dijkstra(start)
print(result[end])
💡소요시간 : 17m