Cod sursa(job #1968255)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 17 aprilie 2017 16:19:58
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

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

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

void input() {
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= m; ++i) {
        int x, y, z; scanf("%d %d %d", &x, &y, &z);
        g[x].push_back({y, z});
    }
}

void run_dijkstra() {
    priority_queue < pair < int, int >, vector < pair < int, int > >, greater < pair < int, int > > > pq;

    memset(dist, inf, sizeof(dist));
    pq.push({0, 1}); dist[1] = 0;

    while (pq.size()) {
        int cost, node; tie(cost, node) = pq.top(); pq.pop();
        if (cost != dist[node]) continue;

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

void output() {
    for (int i = 2; i <= n; ++i)
        printf("%d ", (dist[i] != inf) ? dist[i] : 0);
    printf("\n");
}

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

    input();
    run_dijkstra();
    output();

    return 0;
}