Cod sursa(job #3200513)

Utilizator Mihai_OctMihai Octavian Mihai_Oct Data 4 februarie 2024 21:31:03
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int inf = 1e7 + 2;
int n, m, i, x, y, c;
priority_queue<pair<int, int>> q;
vector<pair<int, int>> a[50002];
int d[50002];

static inline void Calc() {
    int c, x;
    while(!q.empty()) {
        c = q.top().first;
        x = q.top().second;
        q.pop();

        if(d[x] > -c) d[x] = -c;
        if(d[x] >= -c) {
            for(auto it : a[x]) {
                if(d[it.first] == inf) q.push({c - it.second, it.first});
            }
        }
    }
}

int main() {
    fin >> n >> m;
    for(i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        a[x].insert({y, c});
    }

    for(i = 1; i <= n; i++) d[i] = inf;
    q.push({0, 1});
    Calc();

    for(i = 2; i <= n; i++) {
        if(d[i] == inf) fout << "0 ";
        else fout << d[i] << " ";
    }

    return 0;
}