Cod sursa(job #3322492)

Utilizator gabyyy____23Gabriela Madalina Pirvulescu gabyyy____23 Data 14 noiembrie 2025 14:32:24
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

int N, M;

const long long INF = 1e18;

int main() {
    fin >> N >> M;
    vector<vector<pair<int,int>>> g(N+1);
    for (int i = 0; i < M; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        g[a].push_back({b, c});
    }

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

    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<pair<long long,int>>> pq;
    pq.push({0, 1});

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

        if (d != dist[u]) continue;

        for (auto &[v, w] : g[u]) {
            if (dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                pq.push({dist[v], v});
            }
        }
    }

    for (int i = 2; i <= N; i++) {
        if (dist[i] == INF)
            fout << 0 << " ";
        else
            fout << dist[i] << " ";
    }
    fout << "\n";

    return 0;
}