Cod sursa(job #3004409)

Utilizator domistnSatnoianu Dominic Ioan domistn Data 16 martie 2023 12:17:38
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 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];
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 ccost = pq.top().first, cx = pq.top().second;
        pq.pop();

        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] << " ";
    return 0;
}