Cod sursa(job #3335659)

Utilizator vlaxcsVlad Minciunescu vlaxcs Data 23 ianuarie 2026 10:23:48
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

constexpr int NMAX = 5e5 + 5;
constexpr long long INF = 1e18;
int n, m;

struct edge {
    int to;
    long long cost;

    bool operator>(const edge& other) const {
        return cost > other.cost;
    }
};

vector<vector<edge>> a;
vector<long long> d;
vector<int> t;
priority_queue<edge, vector<edge>, greater<>> pq;

void Dijkstra(int s) {
    d[s] = 0;
    pq.push({s, d[s]});

    while (!pq.empty()) {
        const auto current = pq.top().to;
        pq.pop();

        for (const auto [to, cost] : a[current]) {
            if (d[current] + cost < d[to]) {
                d[to] = d[current] + cost;
                t[to] = current;
                pq.push({to, d[to]});
            }
        }
    }

    for (int i = 2; i <= n; ++i) {
        g << d[i] << " ";
    }
}

void init(const int size) {
    a.resize(size);
    d.resize(size, INF);
    t.resize(size);
}

int main() {
    f >> n >> m;
    init(n + 1);
    for (int i = 0;i < m; ++i) {
        int x, y, c;
        f >> x >> y >> c;
        a[x].push_back({y, c});
    }

    Dijkstra(1);

    f.close();
    g.close();
    return 0;
}