Cod sursa(job #2842853)

Utilizator paul911234vaida paul paul911234 Data 1 februarie 2022 17:01:21
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 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]], 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]], 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()) {
        priority_queue<pair<int,int>> aux;
        int lg = elements.size();
        while (lg > 1) {
            aux.push({elements.top().first, elements.top().second});
            elements.pop();
            --lg;
        }
        int val1 = elements.top().first, val2 = elements.top().second;
        swap(aux, elements);
        dijkstra(val2, val1);
    }
    for (int i = 2; i <= n; ++i) {
        if (dist[i] == -1) {
            fout << "0 ";
        } else {
            fout << dist[i] << ' ';
        }
    }
}