Cod sursa(job #2280189)

Utilizator 99Teodor99Bujorean Teodor 99Teodor99 Data 10 noiembrie 2018 12:38:07
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
using namespace std;

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

const int NMax = 5e4 + 5;
const int INF = 1e9;

vector < pair < int, int > > G[NMax];
int D[NMax];

inline void Dijkstra() {
    priority_queue < pair < int, int >, vector < pair < int, int > >, greater < pair < int, int > > > pq;
    pq.emplace(0, 1);

    while(!pq.empty()) {
        int node = pq.top().second;
        int value = pq.top().first;
        pq.pop();

        if(D[node] != value) continue;
        for(auto const &it: G[node]) {
            if(value + it.second < D[it.first]) {
                D[it.first] = value + it.second;
                pq.emplace(D[it.first], it.first);
            }
        }
    }
}

int main(){
    ios::sync_with_stdio(false);

    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= m; i++) {
        int a, b, c;
        fin >> a >> b >> c;

        G[a].push_back({b, c});
    }

    for(int i = 2; i <= n; i++) D[i] = INF;
    Dijkstra();

    for(int i = 2; i <= n; i++) {
        if(D[i] == INF) {
            fout << "0 ";
        } else {
            fout << D[i] << " ";
        }
    }

    return 0;
}