본문 바로가기

백준

1916 최소비용 구하기

다익스트라 연습 문제로 풀어보고 싶었다. 

 

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <string>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
#include <cmath>
#include <cstring>
#include <bitset>
#include <stdio.h>

#define xx first
#define yy second
#define all(x) (x).begin(), (x).end()

using namespace std;
using i64 = long long int;
using ii = pair<int, int>;
using iis = pair<int, string>;
using ii64 = pair<i64, i64>;
using iii = tuple<int, int, int>;

int n, d;

vector<vector<ii>> edge;

vector<int> Dijkstra(int start) {
    vector<int> dist(n+1, -1);
    priority_queue<pair<int, int> > pq; // first : dist , second : vertex_pos
    
    dist[start] = 0;
    pq.push(make_pair(-dist[start], start)); // Min-Heap처럼 사용하기 위해 앞의 거리 인자에 -값을 곱해줌.
    while (!pq.empty()) {
        int here = pq.top().second;
        int heredist = -pq.top().first;
        
        pq.pop();
        if (heredist > dist[here]) 
            continue;
        for (int i = 0; i < edge[here].size(); i++) {
            int there = edge[here][i].first;
            int nextdist = heredist + edge[here][i].second;
            if (dist[there] == -1 || dist[there] > nextdist) { //최단 거리 갱신
                dist[there] = nextdist;
                pq.push(make_pair(-nextdist, there));
            }
        }
    }
    return dist;
}

int main() {
    int m;
    scanf("%d %d", &n, &m);
    
    edge.resize(n + 1);
    for (int i = 0; i < m; i++) {
        int u, v;
        
        scanf("%d %d %d", &u, &v, &d);
        edge[u].push_back(make_pair(v, d));
    }
    
    int start, end;
    scanf("%d %d", &start, &end);
    vector<int> dist = Dijkstra(start);

    cout << dist[end] << endl;
    return 0;
}

'백준' 카테고리의 다른 글

2018 수들의 합 5  (0) 2021.08.01
22352 항체 인식  (0) 2021.08.01
3144 자석  (0) 2021.07.24
16210 DSHS Bank  (0) 2021.07.24
18436 수열과 쿼리 37  (0) 2021.07.24