Cod sursa(job #2172909)

Utilizator cubaLuceafarul cuba Data 15 martie 2018 18:54:10
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int nMax = 50005;
const int inf = 1e9;
int dp[nMax];
struct Vals{
    int nod, cost;
    inline bool operator < (const Vals &A) const {
        return cost > A.cost;
    }
};
priority_queue<Vals> Q;
vector<Vals> G[nMax];
inline void Dij(int start, int n) {
    for(int i = 1; i <= n; i++) {
        dp[i] = inf;
    }
    dp[start] = 0;
    Q.push({start, 0});
    while(!Q.empty()) {
        int nod = Q.top().nod;
        Q.pop();
        for(const auto &v :  G[nod]) {
            int nv = v.nod;
            int cst = v.cost;
            if(dp[nv] > dp[nod] + cst) {
                dp[nv] = dp[nod] + cst;
                Q.push({nv, dp[nv]});
            }
        }
    }
}
int main()
{
    int n, m, x, y, c;
    f >> n >> m;
    for(int i = 1; i <= m; i++) {
        f >> x >> y >> c;
        G[x].push_back({y, c});
    }
    Dij(1, n);
    for(int i = 2; i <= n; i++) {
        if(dp[i] == inf) {
            g << "0 ";
        }
        else {
            g << dp[i] << " ";
        }
    }
    return 0;
}