# 최소비용 구하기 2
import sys
import heapq
input = sys.stdin.readline
MAX = sys.maxsize
N, M = int(input()), int(input())
arr = [[]for _ in range(N+1)]
for _ in range(M):
start, end, cost = map(int, input().split())
arr[start].append((cost, end))
def dijkstra(start):
q = []
heapq.heappush(q, (0, start))
result[start] = 0
while q:
cost, city = heapq.heappop(q)
if result[city] < cost:
continue
for ncost, ncity in arr[city]:
if result[ncity] > cost + ncost:
result[ncity] = cost + ncost
heapq.heappush(q, (result[ncity], ncity))
parent[ncity] = city
start, end = map(int, input().split())
result = [MAX] * (N+1)
parent = [i for i in range(N+1)]
dijkstra(start)
print(result[end])
path = []
temp = end
while True:
path.append(temp)
if temp == parent[temp]:
break
temp = parent[temp]
print(len(path))
path.reverse()
print(*path)
최단거리, 다익스트라
1. 인접리스트로 값을 입력받는다
2. 다익스트라 알고리즘을 실행하면서 parent리스트에 바로 윗부모를 기록해준다
3. 부모를 하나씩 거슬러 올라가면서 path리스트에 저장
4. 각각 출력 (path는 reverse해서 출력)
'Algorithm > BOJ' 카테고리의 다른 글
[백준] 1865번 - 웜홀 (파이썬) (0) | 2022.02.09 |
---|---|
[백준] 1525번 - 퍼즐 (파이썬) (1) | 2022.02.09 |
[백준] 4386번 - 별자리 만들기 (파이썬) (0) | 2022.02.09 |
[백준] 17136번 - 색종이 붙이기 (파이썬) (0) | 2022.02.07 |
[백준] 12738번 - 가장 긴 증가하는 부분 수열 3 (파이썬) (0) | 2022.02.07 |