Cod sursa(job #2802076)

Utilizator MateiDorian123Nastase Matei MateiDorian123 Data 17 noiembrie 2021 14:34:53
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>

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

void dijkstra(vector<vector<pair<int, int>>> &ad, int n, int s){
    /// method to find Dijkstra's shortest path using
    /// in the priority queue we store elements of pair
    /// first -> cost from the start node to the current node
    /// second -> node

    const int INF = 0x3f3f3f3f;
    typedef pair<int, int> my_pair;
    vector<int> dist(n + 1, INF);
    vector<bool>inHeap(n + 1, false);
        priority_queue<my_pair, vector<my_pair>, greater<my_pair>> heap;

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

        while (!heap.empty()) {
            int current = heap.top().second;
            heap.pop();

            if (!inHeap[current]) {
                inHeap[current] = true;

                for (auto &w : ad[current]) {
                    if (dist[current] + w.second < dist[w.first]) {
                        dist[w.first] = dist[current] + w.second;
                        heap.push({dist[w.first], w.first});
                    }
                }
            }
        }

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

int main() {

    int n, m, x, y, cost;
    fin >> n >> m;

    vector<vector<pair<int, int>>> ad(n + 1);

    for (int i = 1; i <= m; ++i) {
        fin >> x >> y >> cost;
        ad[x].push_back({y, cost});
    }


    dijkstra(ad, n, 1);

    return 0;
}