[백준] 11779번 최소비용 구하기 2

JaeYeop·2022년 4월 11일
0

백준

목록 보기
9/19

[문제]

https://www.acmicpc.net/problem/11779

[코드]

import sys
import heapq
INF = int(1e9)
input = sys.stdin.readline

n = int(input())
m = int(input())
graph = [[] for i in range(n + 1)]
for i in range(m):
    u, v, w = map(int, input().split())
    graph[u].append([v, w])
start, stop = map(int, input().split())

def dijkstra(start):
    heap = []
    distance = [INF] * (n + 1)
    distance_path = [[] for i in range(n + 1)]

    heapq.heappush(heap, [0, start, [start]])
    distance[start] = 0
    while heap:
        dist, now, path = heapq.heappop(heap)

        if distance[now] < dist:
            continue

        for i in graph[now]:
            cost = dist + i[1]
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                distance_path[i[0]] = path + [i[0]]
                heapq.heappush(heap, [cost, i[0], distance_path[i[0]]])

    return distance, distance_path

distance, distance_path = dijkstra(start)
print(distance[stop])
print(len(distance_path[stop]))
for i in distance_path[stop]:
    print(i, end=" ")

[풀이]

다익스트라를 활용해서 풀면되는데 다른 문제들과 차이점은 경로를 출력해야한다는 점이다

다익스트라 메소드 안에 distance_path를 정의하고, heap에 넣는 값에 경로 값도 추가한다

이러면 최소 비용의 해가 구해질 때 path도 같이 업데이트 되기 때문에 결과적으로 테이블은 최소 비용, 최소 비용의 경로 이렇게 두가지가 구해진다

profile
이게 왜 틀리지... (나의 메모용 블로그)

0개의 댓글