[파이썬] 백준 11779 : 최소비용 구하기 2 (골드3)
풀이
방향성 생각
최소비용 구하기 1916 이랑 같은 문제.
다익스트라 + 역추적
기존 다익스트라 배열에 previous node를 기록해주는 리스트를 추가한다.
전체코드
import heapq as hq
import sys
input = lambda : sys.stdin.readline().rstrip()
N = int(input())
M = int(input())
G = [[] for _ in range(N+1)]
for _ in range(M):
a,b,cost = map(int,input().split())
G[a].append((b,cost))
start,end = map(int,input().split())
V = [[float('inf'),None]]*(N+1)
V[start] = [0,-1]
heap = [(0,start)]
while heap:
t,x = hq.heappop(heap)
if t > V[x][0]:
continue
for nx, cost in G[x]:
nt = t + cost
if nt < V[nx][0]:
V[nx] = [nt,x]
hq.heappush(heap,(nt,nx))
path = [end]
while True:
px = V[path[-1]][1]
if px == -1:
break
else:
path.append(px)
print(V[end][0])
print(len(path))
print(*path[::-1])
코멘트
- 기본 문제
'Algorithm > Graph' 카테고리의 다른 글
[파이썬] 백준 20304 : 비밀번호 제작 (플레5) (0) | 2024.11.23 |
---|---|
[파이썬] 백준 3197 : 백조의 호수 (플레5) (0) | 2024.11.23 |
[파이썬] 백준 14868 : 문명 (플레4) (0) | 2024.11.22 |
[파이썬] 백준 1916 : 최소비용 구하기 (골드5) (0) | 2024.11.21 |
[파이썬] 백준 1753 : 최단경로 (골드4) (0) | 2024.11.18 |
[파이썬] 백준 2479 : 경로찾기 (골드4) (0) | 2024.11.16 |
[파이썬] 백준 1240 : 노드 사이의 거리 (골드5) (0) | 2024.11.15 |
댓글