Cod sursa(job #3004508)

Utilizator domistnSatnoianu Dominic Ioan domistn Data 16 martie 2023 13:06:45
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

typedef pair<int, int> pii;

const int NMAX = 5e4;

int n, m, dp[NMAX + 1];
bool v[NMAX + 1];
vector<pii> adj[NMAX + 1];
priority_queue<pii, vector<pii>, greater<pii> > pq;

void dijkstra() {
    for(int i = 2; i <= n; ++i) dp[i] = 1e9;
    pq.push({0, 1});
    while(!pq.empty()) {
        const int cx = pq.top().second;
        pq.pop();

        if(v[cx]) continue;
        v[cx] = 1;

        for(const auto &el : adj[cx]) {
            const int ncx = el.first, ncost = el.second;
            if(dp[ncx] > dp[cx] + ncost) {
                dp[ncx] = dp[cx] + ncost;
                pq.push({dp[ncx], ncx});
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for(int i = 1, x, y, cost; i <= m; ++i) {
        fin >> x >> y >> cost;
        adj[x].push_back({y, cost});
    }
    dijkstra();
    for(int i = 2; i <= n; ++i)
        fout << (dp[i] == 1e9 ? 0 : dp[i]) << " ";
    return 0;
}