https://www.acmicpc.net/problem/11779
11779번: 최소비용 구하기 2
첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스
www.acmicpc.net
문제 접근
다익스트라 알고리즘
최소비용 구하기 1916번 문제에서 경로까지 추가해서 출력해야 한다.
경로를 추가하기위해서 경로 변수를 추가해서 각 지점까지 오기위한 바로 전단계 위치를 저장해두면서 풀었다.
코드
import heapq
import sys
input = sys.stdin.readline
"""
다익스트라
visited에 경로까지 추가함.
"""
n = int(input())
m = int(input())
graph = [[] for i in range(n+1)]
INF = float('inf')
for i in range(m):
start, end, weight = map(int,input().split())
graph[start].append((weight, end))
startPoint, endPoint = map(int,input().split())
def dijkstra(sp, ep):
dp = [INF] * (n+1)
dp[sp] = 0
route = [0] * (n+1)
route[sp] = sp
heap = [(0, sp)]
while heap:
w1, s = heapq.heappop(heap)
if dp[s] < w1:
continue
for w2, e in graph[s]:
if dp[e] > w1 + w2:
dp[e] = w1 + w2
route[e] = s
heapq.heappush(heap, (w1 + w2, e))
return dp[ep], route
cost, routes = dijkstra(startPoint, endPoint)
print(cost)
ans = [endPoint]
x = endPoint
while True:
x = routes[x]
ans.append(x)
if x == startPoint:
break
ans.reverse()
if n==1:
print(1)
print(1)
else:
print(len(ans))
print(*ans)
'백준 > 문제풀이_python' 카테고리의 다른 글
1966 프린터 큐 python (0) | 2023.01.12 |
---|---|
12851 숨바꼭질2 python (0) | 2023.01.09 |
1504 특정한 최단 경로 python (0) | 2023.01.08 |
1967 트리의 지름 python (0) | 2023.01.07 |
11724 연결 요소의 개수 python (0) | 2023.01.07 |
댓글