HTD
[Python] 백준 11779번: 최소비용 구하기 2 본문
https://www.acmicpc.net/problem/11779
11779번: 최소비용 구하기 2
첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스
www.acmicpc.net
import sys
import heapq
input = sys.stdin.readline
def getMinCostAndPath(start, end):
dp = [float('inf') for _ in range(n+1)]
todo = [(0, start, [start])]
while todo:
curCost, curNode, curPath = heapq.heappop(todo)
# 우선순위큐로 꺼내므로 최소 비용이 드는 루트를 가장 먼저 방문함
if curNode == end:
return curCost, curPath
if dp[curNode] < curCost:
continue
for adjNode, adjCost in graph[curNode]:
nextCost = curCost + adjCost
if nextCost < dp[adjNode]:
dp[adjNode] = nextCost
heapq.heappush(todo, (nextCost, adjNode, curPath + [adjNode]))
if __name__ == '__main__':
n = int(input())
m = int(input())
graph = [[] for _ in range(n+1)]
for _ in range(m):
s, e, c = map(int, input().split())
graph[s].append((e, c))
start, end = map(int, input().split())
minCost, path = getMinCostAndPath(start, end)
print(minCost)
print(len(path))
print(*path)
다익스트라 알고리즘을 살짝 변형하면 된다. 우선순위큐(todo)에 지금까지 방문했던 노드를 리스트로 기록하는 것을 더해주면 된다.
또, whlie문에서 탐색을 하면서, 현재 노드가 도착 노드와 같을 경우 바로 리턴해준다. 이렇게 해도 되는 이유는, 우선순위큐를 통해 cost가 적은 것부터 탐색을 하기 때문이다.
'Algorithm > 백준' 카테고리의 다른 글
[Python] 백준 13172번: ∑ (0) | 2021.07.25 |
---|---|
[Python] 백준 12851번: 숨바꼭질 2(시간복잡도 2등) (0) | 2021.07.23 |
[Python] 백준 10830번: 행렬 제곱 (0) | 2021.07.21 |
[Python] 백준 5639번: 이진 검색 트리 (0) | 2021.07.20 |
[Python] 백준 2638번: 치즈 (0) | 2021.07.19 |