Cod sursa(job #3159582)

Utilizator aronaronBartha Aron aronaron Data 21 octombrie 2023 17:12:27
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
using PI = pair<int, int>;
using VPI = vector<vector<PI>>;
using VI = vector<int>;

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

const int Inf = 1e9;

int n, m;
VPI G;
VI D;

int main(){
    fin >> n >> m;
    G = VPI(n);
    D = VI(n, Inf);

    int x, y, w;
    for (int i=0; i<m; ++i) {
        fin >> x >> y >> w;
        x--; y--;
        G[x].emplace_back(y, w);
        G[y].emplace_back(x, w);
    }

    priority_queue<PI, vector<PI>, greater<PI>> Q;
    int node = 0;

    D[node] = 0;
    Q.emplace(D[node], node);

    while(!Q.empty()) {
        auto [d, x] = Q.top();
        Q.pop();
        if(d > D[x]) continue;
        for(auto [y, w] : G[x]) {
            if(D[y] > D[x] + w) {
                D[y] = D[x] + w;
                Q.emplace(D[y], y);
            }
        }
    }

    for(VI::iterator it = D.begin()+1; it < D.end(); ++it)
        fout << (*it == Inf ? 0 : *it) << ' ';

    return 0;
}