Cod sursa(job #2172372)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 15 martie 2018 16:13:20
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>

using namespace std;

void do_not_panic() {
    //
}

const int nmax = 5e4 + 10;
const int inf = 0x3f3f3f3f;

int n, m;
int cost[nmax];
vector < pair < int, int > > g[nmax];

priority_queue < pair < int, int >, vector < pair < int, int > >, greater < pair < int, int > >> h;

void run_dijkstra() {
    for (int i = 1; i <= n; ++i)
        cost[i] = inf;

    cost[1] = 0; h.push({cost[1], 1});
    while (h.size()) {
        int cost_node, node;
        tie(cost_node, node) = h.top(); h.pop();

        if (cost_node != cost[node])
            continue;

        for (auto &it: g[node]) {
            if (cost[it.first] < cost[node] + it.second) continue;
            cost[it.first] = cost[node] + it.second;
            h.push({cost[it.first], it.first});
        }
    }

    for (int i = 1; i <= n; ++i)
        if (cost[i] == inf) cost[i] = 0;
}

int main()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);

    ios_base :: sync_with_stdio(false);

    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        cin >> x >> y >> c;
        g[x].push_back({y, c});
    }

    run_dijkstra();
    for (int i = 2; i <= n; ++i)
        cout << cost[i] << ' ';

    return 0;
}