Koala - 16기/코딩테스트 심화 스터디

[백준/C++] 1916번: 최소 비용 구하기

.우디. 2024. 11. 17. 20:23

문제 & 링크

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

 

풀이

1. 정점(도시)의 개수 n과 간선(버스)의 개수 m을 입력받는다.

2. 그래프를 인접 리스트의 형태로 저장한다.

3. 최단 거리 배열인 cost를 큰 값으로 초기화한다.

4. 다익스트라 알고리즘을 사용하여 최단 거리를 탐색한다.

5. 우선 순위 큐를 사용해서 최소 비용부터 탐색한다.

6. 모든 인접 정점을 처리하며 최단거리를 갱신한다.

 

코드

#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];
}