Cod sursa(job #2844847)

Utilizator paul911234vaida paul paul911234 Data 5 februarie 2022 18:22:07
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
#include <fstream>
using namespace std;

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

using ll = long long;

vector<vector<int>> neighbours(50001);
vector<ll> distances(50001, -1);
priority_queue<pair<ll, ll>> elements;

void dijkstra(ll node, ll sum) {
    elements.pop();
    for (int i = 0; i < neighbours[node].size(); i += 2) {
        if (distances[neighbours[node][i]] == -1) {
            // {distance[node],   node}
            distances[neighbours[node][i]] = neighbours[node][i + 1] + sum;
            elements.push({-distances[neighbours[node][i]], neighbours[node][i]});
        } else if (distances[neighbours[node][i]] > neighbours[node][i + 1] + sum) {
            distances[neighbours[node][i]] = neighbours[node][i + 1] + sum;
            elements.push({-distances[neighbours[node][i]], neighbours[node][i]});
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    while (m--) {
        int x, y, cost;
        fin >> x >> y >> cost;
        neighbours[x].push_back(y);
        neighbours[x].push_back(cost);
    }
    // {distance[node],   node}
    elements.push({0, 1});

    while(!elements.empty()) {
            dijkstra(elements.top().second, -elements.top().first);
    }
    for (int i = 2; i <= n; ++i) {
        if (distances[i] == -1) {
            fout << "0 ";
        } else {
            fout << distances[i] << ' ';
        }
    }
    return 0;
}