Cod sursa(job #2842230)

Utilizator lflorin29Florin Laiu lflorin29 Data 31 ianuarie 2022 12:56:58
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>

using namespace std;

/*/
For a given graph G, there must exist at least 1 node "v" that has its out-degree equal to 0.
Then, the topological sort for graph G will be equal to the topological sort for the graph G \ {v} + v /*/

template<class T>
vector<T>operator+(vector<T>v, T delta) {
    for(auto &x : v)
        x = x + delta;
    return v;
}

template<class T>
ostream& operator << (ostream &cout, const vector<T>&v) {
    for(auto x : v)
        cout << x << ' ';
    cout << '\n';
    return cout;
}

class DirectedGraph {
    vector<vector<pair<int, int>>>g;
    int N;
  public:
    DirectedGraph(int N = 0) : g(N), N(N) {};
    void add(int x, int y, int c) {
        assert(0 <= x && x < N);
        assert(0 <= y && y < N);
        g[x].push_back({y, c});
    }
    vector<int>dijkstra() {
        const int INF = 1e9;
        vector<int>d(N, INF);
        d[0] = 0;
        auto cmp = [&] (const int &a, const int &b) {
            return d[a] > d[b];
        };
        priority_queue<int, vector<int>, decltype(cmp)>pq(cmp);
        pq.push(0);
        while(!pq.empty()) {
            int node = pq.top();
            pq.pop();
            for(pair<int, int>p : g[node]) {
                if(d[node] + p.second < d[p.first]) {
                    d[p.first] = d[node] + p.second;
                    pq.push(p.first);
                }
            }
        }
        return d;
    }
};
int main() {
    ifstream cin("dijkstra.in");
    ofstream cout("dijkstra.out");

    int n, m;
    cin >> n >> m;

    DirectedGraph DG(n);
    for(int i = 0; i < m; ++i) {
        int x, y, c;
        cin >> x >> y >> c;
        DG.add(x - 1, y - 1, c);
    }

    vector<int>d = DG.dijkstra();
    d.erase(d.begin());
    cout << d;
}