728x90
https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
위의 문제는 데이크스트라 알고리즘인 최단경로 알고리즘 문제를 풀고 오면 똑같은 방식으로 문제를 해결 할 수 있다.
우선순위큐로 가장 짧은 거리인 노드부터 방문하고, 방문하려는 거리가 이미 더 짧은 거리라면 탐색을 멈춘다.
https://bigkwangs.tistory.com/23
[백준] 1753번 : 최단경로
https://www.acmicpc.net/problem/1753 1753번: 최단경로 첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘
bigkwangs.tistory.com
위의 문제를 먼저 보고 오면 문제를 쉽게 이해 할 수 있다.
import heapq
INF = int(10e9)
N = int(input()) # 도시의 개수 ( 정점의 개수 )
M = int(input()) # 버스의 개수 ( 간선의 개수 )
graph = [[] for _ in range(N+1)]
for _ in range(M):
start, end , cost = map(int, input().split())
graph[start].append([end, cost]) # 끝, 비용
start , end = map(int, input().split())
distance = [INF for _ in range(N+1)]
queue = []
distance[start] = 0
heapq.heappush(queue, [distance[start], start])
while queue:
cost, city = heapq.heappop(queue)
if distance[city] > cost:
continue
for city2, cost2 in graph[city]:
if distance[city2] > cost2 + cost:
distance[city2] = cost2 + cost
heapq.heappush(queue, [distance[city2], city2])
print(distance[end])
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 2293번 : 동전 1 (0) | 2023.07.16 |
---|---|
[백준] 11066번 : 파일 합치기 (0) | 2023.07.16 |
[백준] 1753번 : 최단경로 (0) | 2023.07.15 |
[백준] 1520번 : 내리막길 (2) | 2023.07.15 |
[백준] 9252번 : LCS2 (1) | 2023.07.14 |