CP-Library

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

View the Project on GitHub taisa1/CP-Library

:heavy_check_mark: Graph/Dijkstra.cpp

Back to top page

Description

グラフ G を管理する。
addedge(u,v,c) : Gに有向辺 (u,v) を張る。
dijkstra(st) : G における、頂点 st から全ての点への最短路の長さを返す。

Verified with

Code

//@docs Docs/Dijkstra.md
template <class T>
struct Dijkstra {
    int n;
    vector<vector<pair<T, int>>> G;
    Dijkstra(int n) : n(n), G(n) {}
    void addedge(const int &u, const int &v, const T &c) { G[u].emplace_back(v, c); }
    vector<T> dijkstra(const int &st) {
        priority_queue<pair<T, int>, vector<pair<T, int>>, greater<pair<T, int>>> q;
        vector<T> d(n, INF);
        d[st] = 0;
        q.emplace(0, st);
        while (!q.empty()) {
            int v = q.top().second;
            T dd = q.top().first;
            q.pop();
            if (d[v] < dd) continue;
            for (auto &e : G[v]) {
                if (d[e.first] > d[v] + e.second) {
                    d[e.first] = d[v] + e.second;
                    q.emplace(d[e.first], e.first);
                }
            }
        }
        return d;
    }
};

#line 1 "Graph/Dijkstra.cpp"
//@docs Docs/Dijkstra.md
template <class T>
struct Dijkstra {
    int n;
    vector<vector<pair<T, int>>> G;
    Dijkstra(int n) : n(n), G(n) {}
    void addedge(const int &u, const int &v, const T &c) { G[u].emplace_back(v, c); }
    vector<T> dijkstra(const int &st) {
        priority_queue<pair<T, int>, vector<pair<T, int>>, greater<pair<T, int>>> q;
        vector<T> d(n, INF);
        d[st] = 0;
        q.emplace(0, st);
        while (!q.empty()) {
            int v = q.top().second;
            T dd = q.top().first;
            q.pop();
            if (d[v] < dd) continue;
            for (auto &e : G[v]) {
                if (d[e.first] > d[v] + e.second) {
                    d[e.first] = d[v] + e.second;
                    q.emplace(d[e.first], e.first);
                }
            }
        }
        return d;
    }
};

Back to top page