Cod sursa(job #3359714)

Utilizator VladPislaruPislaru Vlad Rares VladPislaru Data 2 iulie 2026 21:26:57
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int INF = 0x3f3f3f3f; // ~1.06e9, mai mare decat orice distanta reala posibila

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

    int N, M;
    fin >> N >> M;

    vector<vector<pair<int,int>>> adj(N + 1); // adj[u] = lista de perechi (vecin, cost)
    for (int i = 0; i < M; ++i) {
        int a, b, c;
        fin >> a >> b >> c;
        adj[a].push_back({b, c});
    }

    vector<int> dist(N + 1, INF);
    dist[1] = 0;

    // min-heap de perechi (distanta, nod)
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
    pq.push({0, 1});

    while (!pq.empty()) {
        int d = pq.top().first;
        int u = pq.top().second;
        pq.pop();

        if (d > dist[u]) continue; // intrare invechita in heap, nodul e deja finalizat

        for (const auto &e : adj[u]) {
            int v = e.first, w = e.second;
            if (d + w < dist[v]) {
                dist[v] = d + w;
                pq.push({dist[v], v});
            }
        }
    }

    for (int i = 2; i <= N; ++i)
        fout << (dist[i] == INF ? 0 : dist[i]) << (i < N ? ' ' : '\n');

    return 0;
}