Cod sursa(job #2923562)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 15 septembrie 2022 19:54:57
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
#define INFILE "dijkstra.in"
#define OUTFILE "dijkstra.out"
#define DIM 50005
#define INF 0x3f3f3f3f

using namespace std;

ifstream f(INFILE);
ofstream g(OUTFILE);

struct elem {
    int node;
    int cost;

    bool operator < (const elem &x) const {
        return cost < x.cost;
    }
};

int n, m;
int dist[DIM];
vector <elem> edges[DIM];
priority_queue <elem> pq;

void dijkstra() {

    dist[1] = 0;
    pq.push({1, 0});

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

        if (cost > dist[node])
            continue ;

        for (auto k: edges[node]) {
            if (dist[k.node] > k.cost + cost) {
                dist[k.node] = k.cost + cost;
                pq.push(k);
            }
        }
    }
}

int main() {

    f >> n >> m;

    for (int i = 1; i <= m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        edges[x].push_back({y, c});
    }

    for (int i = 1; i <= n; i++)
        dist[i] = INF;

    dijkstra();

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

    return 0;
}