Cod sursa(job #3348223)

Utilizator radeuojArghira Radu Stefan radeuoj Data 20 martie 2026 11:57:00
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <vector>
#include <queue>

const int MAX_N = 50000;
const int MAX_M = 250000;
const long INF = 1e15;

struct Edge {
    int v;
    long c;
};

struct Node {
    std::vector<Edge> adj;
    long dist;
};

int n, m;
Node a[MAX_N + 1];

void read_graph() {
    for (int i = 0; i < m; i++) {
        int u, v, c;
        std::cin >> u >> v >> c;
        a[u].adj.push_back({ v, c });
    }
}

void reset_distances() {
    for (int i = 1; i <= n; i++) {
        a[i].dist = INF;
    }
}

void dijkstra() {
    struct DijkstraNode {
        int u;
        long d;

        bool operator<(const DijkstraNode& other) const {
            return d > other.d || (d == other.d && u < other.u);
        }
    };

    std::priority_queue<DijkstraNode> pq;
    a[1].dist = 0;
    pq.push({ 1, 0 });

    while (!pq.empty()) {
        auto [u, d] = pq.top();
        pq.pop();

        if (a[u].dist != d) {
            continue;
        }

        for (auto [v, c] : a[u].adj) {
            if (a[u].dist + c < a[v].dist) {
                a[v].dist = a[u].dist + c;
                pq.push({ v, a[v].dist });
            }
        }
    }
}

void print_distances() {
    for (int i = 2; i <= n; i++) {
        std::cout << a[i].dist << ' ';
    }
}

int main() {
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    std::cin >> n >> m;
    read_graph();
    reset_distances();
    dijkstra();
    print_distances();
}