Cod sursa(job #3280606)

Utilizator alexdumitruAlexandru Dumitru alexdumitru Data 26 februarie 2025 19:06:28
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <array>

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

using ll = long long;

const ll INF = 1e15;
const int MAX_N = 50000;
int n, m;

std::vector<std::array<int, 2>> g[MAX_N + 1];

void read() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int u, v, c;
        fin >> u >> v >> c;
        g[u].push_back({v, c});
        g[v].push_back({u, c});
    }
}

bool vis[MAX_N + 1];
ll d1[MAX_N + 1];

struct cmp {
    ll *d;
    bool operator() (int x, int y) const {
        return d[x] > d[y];
    }
    cmp(ll* _d): d(_d) {}
};

void dijkstra(int src, ll d[]) {
    for (int i = 1; i <= n; i++) {
        vis[i] = false;
        d[i] = INF;
    }

    d[src] = 0;

    std::priority_queue<int, std::vector<int>, cmp> pq((cmp(d)));
    pq.push(src);

    while (!pq.empty()) {
        int node = pq.top();
        pq.pop();
        if (vis[node])
            continue;
        vis[node] = true;

        for (auto [to, c] : g[node]) {
            if (d[node] + c < d[to]) {
                d[to] = d[node] + c;
                pq.push(to);
            }
        }
    }
}

void solve() {
    dijkstra(1, d1);
}

void write() {
    for (int i = 2; i <= n; i++)
        fout << (d1[i] == INF ? 0 : d1[i]) << ' ';
}

signed main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
    read();
    solve();
    write();
    return 0;
}