Cod sursa(job #2982883)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 21 februarie 2023 01:32:05
Problema Algoritmul lui Dijkstra Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <queue>
#define DIM 50005
#define INF 0x3f3f3f3f

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

struct elem {
    int node, cost;

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

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

void dijkstra(int node) {
    pq.push({node, 0});
    while (!pq.empty()) {
        int node = pq.top().node;
        int cost = pq.top().cost;
        pq.pop();

        if (cost > dist[node])
            continue;

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

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(1);

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

    return 0;
}