Cod sursa(job #3378158)

Utilizator IanisCijuCiju Ianis-Cristian IanisCiju Data 25 noiembrie 2026 13:24:39
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int INF = 1000000000;

int main() {
    int n, m;
    f >> n >> m;

    vector<vector<pair<int,int>>> g(n + 1);
    for (int i = 0; i < m; i++) {
        int a, b, c;
        f >> a >> b >> c;
        g[a].push_back({b, c});
    }

    vector<int> d(n + 1, INF);
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;

    d[1] = 0;
    pq.push({0, 1});

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

        if (cost > d[nod])
            continue;

        for (auto &p : g[nod]) {
            int vecin = p.first;
            int c = p.second;
            if (d[nod] + c < d[vecin]) {
                d[vecin] = d[nod] + c;
                pq.push({d[vecin], vecin});
            }
        }
    }

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