Cod sursa(job #3272274)

Utilizator sstanciu44Stanciu Sebastian sstanciu44 Data 29 ianuarie 2025 01:21:41
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

int main() {
    int n, m, i, x, y, c;
    f >> n >> m;

    vector<vector<pair<int, int>>> edges(n + 1);
    vector<int> d(n + 1, INT_MAX);
    vector<int> p(n + 1, -1);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

    for(i = 0; i < m; ++i) {
        f >> x >> y >> c;
        edges[x].push_back({y, c});
        //edges[y].push_back({x, c});
    }

    d[1] = 0;
    pq.push({0, 1});

    while(!pq.empty()) {
        int currentNode = pq.top().second, currentDist = pq.top().first;
        pq.pop();

        if(d[currentNode] != currentDist)
            continue;

        for(auto& edge: edges[currentNode]) {
            int dist = edge.second, to = edge.first;
            if(d[currentNode] + dist < d[to]) {
                d[to] = d[currentNode] + dist;
                p[to] = currentNode;
                pq.push({d[to], to});
            }
        }
    }

    for(i = 2; i <= n; ++i)
        g << d[i] << ' ';

    return 0;
}