1일1알

백준 5972번 택배 배송 C++ 본문

알고리즘

백준 5972번 택배 배송 C++

영춘권의달인 2022. 9. 10. 13:24

출처 : https://www.acmicpc.net/problem/5972

 

다익스트라

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>

using namespace std;
using int64 = long long;

int n, m;

struct VertexCost {
    int64 vertex;
    int64 cost;
    bool operator<(const VertexCost& other) const {
        return cost < other.cost;
    }
    bool operator>(const VertexCost& other) const {
        return cost > other.cost;
    }
};

vector<vector<pair<int64, int64>>> graph;

void Dijkstra(int64 start) {
    vector<int64> best(n + 1, INT_MAX);
    priority_queue<VertexCost, vector<VertexCost>, greater<VertexCost>> pq;

    pq.push({ start,0 });
    best[start] = 0;

    while (!pq.empty()) {
        auto curr = pq.top();
        pq.pop();

        if (curr.cost > best[curr.vertex]) continue;

        for (auto next : graph[curr.vertex]) {
            if (best[next.first] <= curr.cost + next.second) continue;

            best[next.first] = curr.cost + next.second;
            pq.push({ next.first,curr.cost + next.second });
        }
    }
    cout << best[n];
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    cin >> n >> m;
    graph = vector<vector<pair<int64, int64>>>(n + 1, vector<pair<int64, int64>>());
    for (int i = 0; i < m; i++) {
        int64 start, end, cost;
        cin >> start >> end >> cost;
        graph[start].push_back({end,cost});
        graph[end].push_back({start,cost});
    }
    Dijkstra(1);
}

'알고리즘' 카테고리의 다른 글

백준 1939번 중량제한 C++  (0) 2022.09.13
백준 17478번 재귀함수가 뭔가요? C++  (0) 2022.09.12
백준 1253번 좋다 C++  (0) 2022.09.09
백준 24391번 귀찮은 해강이 C++  (0) 2022.09.08
백준 2607번 비슷한 단어 C++  (0) 2022.09.07