문제 출처 : www.acmicpc.net/problem/11779
11779번: 최소비용 구하기 2
첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스
www.acmicpc.net
문제 해석 : 출발점에서 목적지까지 가는 경로와 비용이 주어 졌을때 최소 비용과 거치는 정점수, 정점을 출력하는 문제이다.
문제 풀이 : 다익스트라 알고리즘을 통해서 최소비용을 구하고, 중간에 경로를 기록하면 된다.
풀이 코드
def dijkstra(s):
distance = [INF] * (N+1)
distance_path = [[] for _ in range(N+1)]
q = [[0, s, [s]]]
distance[s] = 0
while q:
now_cost, now_vertex, path = heapq.heappop(q)
for next_cost, next_vertex in Q[now_vertex]:
if next_cost + now_cost < distance[next_vertex]:
next_cost += now_cost
distance[next_vertex] = next_cost
distance_path[next_vertex] = path + [next_vertex]
heapq.heappush(q, [next_cost, next_vertex, path + [next_vertex]])
return distance, distance_path
import sys, heapq
INF = sys.maxsize
N = int(input())
M = int(input())
Q = [[] for _ in range(N+1)]
for _ in range(M):
start, end, cost = map(int, input().split())
Q[start].append([cost, end])
S, E = map(int, input().split())
answer, answer_path = dijkstra(S)
print(answer[E])
print(len(answer_path[E]))
for element in answer_path[E]:
print(element, end = " ")
author : donghak park
contact : donghark03@naver.com
## 문제의 저작권은 백준 알고리즘 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.
'📊알고리즘, 문제풀이 > 📈문제풀이 (PS)' 카테고리의 다른 글
[알고리즘][Python] 백준 12851 숨바꼭질 2 문제 풀이 (0) | 2021.01.29 |
---|---|
[알고리즘][Python] 백준 15654 N과 M (5) 문제 풀이 (0) | 2021.01.28 |
[알고리즘][Python] 백준 11725 트리의 부모 찾기 문제 풀이 (0) | 2021.01.28 |
[알고리즘][Python] 백준 11660 구간 합 구하기 5 문제 풀이 (0) | 2021.01.28 |
[알고리즘][Python] 백준 9251 LCS 문제 풀이 (0) | 2021.01.27 |