Cod sursa(job #2844225)

Utilizator paul911234vaida paul paul911234 Data 3 februarie 2022 23:28:10
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <queue>
#include <vector>
#include <utility>
#include <fstream>
using namespace std;

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

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

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

int main() {
    int n, m;
    fin >> n >> m;
    for (int i = 1, x, y, z; i <= m; ++i) {
        fin >> x >> y >> z;
        neighbours[x].push_back(y);
        neighbours[x].push_back(z);
    }
    elements.push({0, 1});
    dist[1] = 0;
    while (!elements.empty()) {
        dijkstra(elements.top().second, dist[elements.top().second]);
        elements.pop();

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