cpplib

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub morioprog/cpplib

:heavy_check_mark: ダイクストラ法
(graph/shortestpath/dijkstra.hpp)

概要

単一始点最短路. 辺の重みが非負である必要がある.

計算量

$O(E\log V)$

使用例

Verified with

Code

/**
* @brief ダイクストラ法
* @docs docs/graph/shortestpath/dijkstra.md
*/

template <typename T>
vector<T> dijkstra(const Graph<T>& g, int frm) {
    using P = pair<T, int>;
    vector<T> ret(g.V, GINF<T>);
    ret[frm] = 0;
    priority_queue<P, vector<P>, greater<P>> pq;
    pq.emplace(ret[frm], frm);
    while (not pq.empty()) {
        T cst;
        int idx;
        tie(cst, idx) = pq.top();
        pq.pop();
        if (ret[idx] < cst) continue;
        for (auto& e : g.mat[idx]) {
            T nxt_cst = cst + e.cst;
            if (ret[e.to] <= nxt_cst) continue;
            ret[e.to] = nxt_cst;
            pq.emplace(ret[e.to], e.to);
        }
    }
    return ret;
}
#line 1 "graph/shortestpath/dijkstra.hpp"
/**
* @brief ダイクストラ法
* @docs docs/graph/shortestpath/dijkstra.md
*/

template <typename T>
vector<T> dijkstra(const Graph<T>& g, int frm) {
    using P = pair<T, int>;
    vector<T> ret(g.V, GINF<T>);
    ret[frm] = 0;
    priority_queue<P, vector<P>, greater<P>> pq;
    pq.emplace(ret[frm], frm);
    while (not pq.empty()) {
        T cst;
        int idx;
        tie(cst, idx) = pq.top();
        pq.pop();
        if (ret[idx] < cst) continue;
        for (auto& e : g.mat[idx]) {
            T nxt_cst = cst + e.cst;
            if (ret[e.to] <= nxt_cst) continue;
            ret[e.to] = nxt_cst;
            pq.emplace(ret[e.to], e.to);
        }
    }
    return ret;
}
Back to top page