Cod sursa(job #3165086)

Utilizator octavian202Caracioni Octavian Luca octavian202 Data 5 noiembrie 2023 13:40:19
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

#define ll long long

using namespace std;

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

const ll NMAX = 50003, INF = 1e12;
vector<pair<ll, ll> > g[NMAX]; // cost, nod
ll d[NMAX], n;

void dijkstra(ll s) {
    for (ll i = 1; i <= n; i++)
        d[i] = INF;
    d[s] = 0;

    priority_queue<pair<ll, ll>, vector<pair<ll, ll> >, greater<pair<ll, ll> > > pq;
    pq.push(make_pair(0, s));

    while (!pq.empty()) {
        ll curr = pq.top().second, cv = pq.top().first;
        pq.pop();

        if (d[curr] < cv)
            continue;

        for (auto nxt : g[curr]) {
            ll nod = nxt.first, cost = nxt.second;
            if (d[curr] + cost < d[nod]) {
                d[nod] = d[curr] + cost;
                pq.push(make_pair( d[nod], nod));
            }
        }
    }
}

int main() {

    ll m;
    fin >> n >> m;
    while (m--) {
        ll x, y, c;
        fin >> x >> y >> c;
        g[x].push_back(make_pair(y, c));
    }

    dijkstra(1);
    for (ll i = 2; i <= n; i++)
        fout << d[i] << ' ';


    return 0;
}