Cod sursa(job #3325333)

Utilizator iamsiulStaicu Octavian iamsiul Data 25 noiembrie 2025 12:38:03
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int inf = 2000000000;
int n, m;
int d[50005];
vector<pair<int, int>> a[50005];

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

    for (int i = 1; i <= n; i++) d[i] = inf;

    priority_queue<pair<int, int>> q;
    d[1] = 0;
    q.push({0, 1});

    while (!q.empty()) {
        int cost = -q.top().first;
        int nod = q.top().second;
        q.pop();

        if (cost > d[nod]) continue;

        for (auto p : a[nod]) {
            int vecin = p.first;
            int cost_arc = p.second;
            if (d[nod] + cost_arc < d[vecin]) {
                d[vecin] = d[nod] + cost_arc;
                q.push({-d[vecin], vecin});
            }
        }
    }

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

    return 0;
}