Cod sursa(job #2798779)

Utilizator vansJos da pa perete vans Data 11 noiembrie 2021 21:05:49
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> pii;

const int NMAX = 5e4, MMAX = 25e4;

int n, m, ans[NMAX + 1];
vector<pii> adj[NMAX + 1];

void dij(const int SN = 1) {
    priority_queue<pii, vector<pii>, greater<pii> > q;
    q.push({0, SN});

    for(int i = 2; i <= n; ++i)
        ans[i] = 2e9;

    while(!q.empty()) {
        const int crt = q.top().second;
        q.pop();

        for(const auto &el : adj[crt]) {
            const int ncrt = el.first, ncost = el.second;
            if(ans[ncrt] > ans[crt] + ncost) {
                ans[ncrt] = ans[crt] + ncost;
                q.push({ans[ncrt], ncrt});
            }
        }
    }
}

int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    scanf("%d%d", &n, &m);
    while(m--) {
        int x, y, z;
        scanf("%d%d%d", &x, &y, &z);
        adj[x].push_back({y, z});
    }
    dij();
    for(int i = 2; i <= n; ++i)
        printf("%d ", ans[i] = (ans[i] == 2e9 ? 0 : ans[i]));
    return 0;
}