728x90
백준 1916번 최소비용 구하기 문제 해설
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
모든 도시의 이동 비용이 양의 정수이고, 시작 지점에 대한 정보도 있으므로 해당 문제는 다익스트라 알고리즘을 활용하여 해결하면 된다.
다익스트라 알고리즘에 대한 설명은 다음을 참조하면 된다. 다익스트라 알고리즘 개념, 다익스트라 알고리즘 실습
다익스트라 알고리즘을 활용하여 코드를 작성하면 다음과 같다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)
n = int(input())
m = int(input())
graph = [[] for _ in range(n+1)]
distance = [INF] * (n+1)
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b,c))
start, end= map(int, input().split())
def Dijkstra(start):
q = []
heapq.heappush(q, (0,start))
distance[start] = 0
while q:
dist, now = heapq.heappop(q)
if distance[now] < dist:
continue
for i in graph[now]:
cost = dist + i[1]
if cost < distance[i[0]]:
distance[i[0]] = cost
heapq.heappush(q, (cost, i[0]))
Dijkstra(start)
print(distance[end])
|
해당 문제는 다익스트라 알고리즘을 구현할 수 있는지에 대해 물어보는 문제로 다익스트라 알고리즘을 구현하여 해결하였다.
728x90
'취업을 준비하며 정리하는 컴퓨터 지식 > Problem Solving' 카테고리의 다른 글
[ProblemSolving] 백준 1744번 수 묶기 문제풀이 (0) | 2021.02.05 |
---|---|
[ProblemSolving] 백준 7576번 토마토 문제풀이 (0) | 2021.02.04 |
[Problem Solving] 백준 1092번 배 문제풀이 (2) | 2021.02.01 |
[ProblemSolving] 백준 2589번 보물섬 문제풀이 (0) | 2021.01.29 |
[ProblemSolving] 백준 2667번, 프로그래머스 64061번 문제풀이 (0) | 2021.01.27 |