[백준/C++] 1916번: 최소 비용 구하기
[백준/C++] 1916번: 최소 비용 구하기
문제 & 링크
https://www.acmicpc.net/problem/1916
풀이
정점(도시)의 개수 n과 간선(버스)의 개수 m을 입력받는다.
그래프를 인접 리스트의 형태로 저장한다.
최단 거리 배열인 cost를 큰 값으로 초기화한다.
다익스트라 알고리즘을 사용하여 최단 거리를 탐색한다.
우선 순위 큐를 사용해서 최소 비용부터 탐색한다.
모든 인접 정점을 처리하며 최단거리를 갱신한다.
코드
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
int cost[1001];
vector<pair<int, int>> V[1001];
void dijkstra(int a) {
priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int, int>>> pq;
pq.push(make_pair(0, a));
cost[a] = 0;
while (!pq.empty())
{
int c = pq.top().first;
int x = pq.top().second;
pq.pop();
if (cost[x] < c)
continue;
for (int i = 0; i < V[x].size(); i++){
int nx = V[x][i].first;
int nc = c + V[x][i].second;
if (cost[nx] > nc){
pq.push(make_pair(nc, nx));
cost[nx] = nc;
}
}
}
}
int main(){
int n, m;
cin >> n >> m;
V[0].push_back(make_pair(0, 0));
memset(cost, 98765432, sizeof(cost));
for (int i = 0; i < m; i++){
int a, b, c;
cin >> a >> b >> c;
V[a].push_back(make_pair(b, c));
}
int st, dt;
cin >> st >> dt;
dijkstra(st);
cout << cost[dt];
}
This post is licensed under CC BY 4.0 by the author.
