Cod sursa(job #2896900)

Utilizator preda.andreiPreda Andrei preda.andrei Data 1 mai 2022 14:20:43
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <cstdint>
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

using Graph = vector<vector<pair<int, int64_t>>>;

vector<int64_t> Solve(const Graph& graph) {
    constexpr int64_t kInf = 1LL << 60;
    vector<int64_t> dist(graph.size(), kInf);
    dist[0] = 0;

    queue<int> q;
    q.push(0);

    vector<bool> in_q(graph.size(), false);
    in_q[0] = true;

    for (; !q.empty(); q.pop()) {
        auto node = q.front();
        in_q[node] = false;

        for (const auto& [next, cost] : graph[node]) {
            if (dist[node] + cost < dist[next]) {
                dist[next] = dist[node] + cost;
                if (!in_q[next]) {
                    q.push(next);
                    in_q[next] = true;
                }
            }
        }
    }

    vector<int64_t> res(graph.size() - 1);
    for (size_t i = 1; i < graph.size(); i += 1) {
        res[i - 1] = dist[i] < kInf ? dist[i] : 0;
    }
    return res;
}

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

    int nodes, edges;
    fin >> nodes >> edges;

    Graph graph(nodes);
    for (int i = 0; i < edges; i += 1) {
        int64_t a, b, cost;
        fin >> a >> b >> cost;
        graph[a - 1].push_back({b - 1, cost});
        graph[b - 1].push_back({a - 1, cost});
    }

    auto res = Solve(graph);
    for (const auto& dist : res) {
        fout << dist << " ";
    }
    fout << "\n";

    return 0;
}