Cod sursa(job #2268093)

Utilizator SemetgTemes George Semetg Data 24 octombrie 2018 14:50:13
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <iostream>
#include <climits>
#include <vector>
#include <queue>
using namespace std;

#define PI pair<int, int>

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

int n;
vector<PI> graf[50005];
vector<int> d(50005, INT_MAX);

void citeste() {
    int m;
    in >> n >> m;
    
    while (m--) {
        int i, j, c;
        in >> i >> j >> c;
        graf[i].push_back({ c, j });
    }
}

void Dijkstra() {
    priority_queue<PI, vector<PI>, greater<PI>> q;
    q.push({ 0, 1 });
    d[1] = 0;
    
    while (!q.empty()) {
        int start = q.top().second;
        q.pop();
        
        for (auto& i : graf[start]) {
            int nod = i.second, cost = i.first;
            
            if (d[nod] > d[start] + cost) {
                d[nod] = d[start] + cost;
                q.push({ d[nod], nod });
            }
        }
    }
}

void afiseaza() {
    for (int i { 2 }; i <= n; ++i)
        out << (d[i] == INT_MAX ? 0 : d[i]) << ' ';
}

int main() {
    citeste();
    Dijkstra();
    afiseaza();
}