Cod sursa(job #3357995)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:44:53
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <limits>

using namespace std;

const int INF = numeric_limits<int>::max();

struct Edge {
    int node, cost;
};

struct Compare {
    bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
        return a.second > b.second;
    }
};

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

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

    vector<vector<Edge>> graph(N + 1);
    for (int i = 0; i < M; i++) {
        int A, B, C;
        fin >> A >> B >> C;
        graph[A].push_back({B, C});
    }

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

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

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

        if (cost > distances[node]) continue;

        for (const auto& edge : graph[node]) {
            int newCost = cost + edge.cost;
            if (newCost < distances[edge.node]) {
                distances[edge.node] = newCost;
                pq.push({edge.node, newCost});
            }
        }
    }

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

    fin.close();
    fout.close();

    return 0;
}