Cod sursa(job #2465396)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 30 septembrie 2019 08:30:53
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#define pb push_back

using namespace std;

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

struct Elem {
    int node, cost;
    bool operator<(const Elem &other) const {
        if (cost != other.cost)
            return cost < other.cost;
        return node < other.node;
    }
};

const int MAXN = 5 * 1e4 + 10, INF = 0x3f3f3f3f;
int distances[MAXN], n, m;
vector<Elem> edges[MAXN];
set<Elem> heap;

void read() {
    int x, y, cost;
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        fin >> x >> y >> cost;
        edges[x].pb({y, cost});
    }
}

void initialize() {
    for (int i = 1; i <= n; ++i)
        distances[i] = INF;
}

void solve() {
    heap.insert({1, 0});
    distances[1] = 0;
    while (!heap.empty()) {
        Elem el;
        el.cost = heap.begin()->cost;
        el.node = heap.begin()->node;
        heap.erase(heap.begin());
        for (auto &it: edges[el.node]) {
            if (distances[el.node] + it.cost < distances[it.node]) {
                distances[it.node] = distances[el.node] + it.cost;
                heap.insert({it.node, distances[it.node]});
            }
        }
    }
}

void print() {
    for (int i = 2; i <= n; ++i)
        fout << distances[i] << ' ';
}

int main() {
    read();
    initialize();
    solve();
    print();
    return 0;
}