Cod sursa(job #2940442)

Utilizator mockupMockup mockup Data 15 noiembrie 2022 16:31:15
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <queue>
#include <vector>
#include <climits>
#include <iostream>
#include <fstream>

std::ifstream fin("dijkstra.in");
std::ofstream fout("dijkstra.out");
#define cin fin
#define cout fout
using namespace std;

#define INF LLONG_MAX
int n, m;
std::vector<long long int> dist;
std::vector<std::vector<std::pair<int, long long int>>> neighs;

void dijkstra(int head) {
    auto comp = [&](int const& a, int const& b) {
        // min heap
        return dist[a] > dist[b];
    };
    std::priority_queue<int, std::vector<int>, decltype(comp)> pq(comp);

    dist[head] = 0;
    pq.push(head);

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

        for (auto& neigh : neighs[node]) {
            if (dist[neigh.first] > dist[node] + neigh.second) {
                dist[neigh.first] = dist[node] + neigh.second;

                pq.push(neigh.first);
            }
        }
    }

    // for (int i = 0; i < n; ++i) {
    //     cout << dist[i] << ' ';
    // }
    for (int i = 1; i < n; ++i) {
        if (dist[i] != INF) {
            cout << dist[i] << ' ';
        } else {
            cout << 0 << ' ';
        }
    }
}

int main() {
    cin >> n >> m;
    dist.resize(n, INF);
    neighs.resize(n);

    for (int i = 0, x, y, c; i < m; ++i) {
        cin >> x >> y >> c;

        --x;
        --y;
        neighs[x].push_back({y, c});
        neighs[y].push_back({x, c});
    }

    dijkstra(0);

    return 0;
}