Cod sursa(job #2843816)

Utilizator mediocrekarmaChirvasa George Matei mediocrekarma Data 2 februarie 2022 23:14:02
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
//#include "pch.h"
//#include <bits/stdc++.h>
#include <fstream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
typedef pair<int, int> PII;

const int N_MAX = 50000;
vector<pair<int, int>> adjList[N_MAX + 1];
int dist[N_MAX + 1];

void dijkstra(const int& start) {
    priority_queue <PII, vector<PII>, greater<PII>> pq;
    dist[start] = 0;
    // cost before node index so we can use the built-in 'greater' 
    pq.push(make_pair(0, start)); 
    while (!pq.empty()) {
        auto [cost, node] = pq.top(); 
        pq.pop();
        if (cost > dist[node]) {
            continue;
        }
        for (const auto& [newNode, newCost] : adjList[node]) {
            if (dist[newNode] > dist[node] + newCost) {
                dist[newNode] = dist[node] + newCost;
                pq.push(make_pair(dist[newNode], newNode));
            }
        }

    }
}

int main() {
    ios_base::sync_with_stdio(0);
    fin.tie(0);
    int n, m;
    fin >> n >> m;
    fill(dist, dist + n + 1, INT_MAX);
    while (m--) {
        uint16_t x, y, cost;
        fin >> x >> y >> cost;
        adjList[x].push_back(make_pair(y, cost));
    }
    dijkstra(1);
    for (int i = 2; i <= n; ++i) {
        if (dist[i] == INT_MAX) {
            fout << "0 ";
        } else {
            fout << dist[i] << ' ';
        }
    }
}