Cod sursa(job #3358355)

Utilizator NFJJuniorIancu Ivasciuc NFJJunior Data 16 iunie 2026 14:35:55
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
// Dijkstra's Algorithm
//
// Given a graph where all edges have a non-negative weight, compute the
// shortest distances from a given source vertex s to all other vertices.
//
// Complexity:
// - dense graphs: O(N^2 + M)
// - sparse graphs: O(MlogN)
// - fibonacci heap: O(NlogN)

#include <bits/stdc++.h>
using namespace std;

int n, m;
vector<vector<pair<int, int>>> adj;
vector<int> parent;
vector<int> dist;

void dijkstra(int start)
{
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        pq;

    dist[start] = 0;
    pq.push({0, start});

    while (!pq.empty()) {
        auto [node_dist, node] = pq.top();
        pq.pop();

        if (node_dist != dist[node])
            continue;

        for (auto [next, weight] : adj[node]) {
            int next_dist = node_dist + weight;
            if (next_dist < dist[next]) {
                parent[next] = node;
                dist[next] = next_dist;
                pq.push({next_dist, next});
            }
        }
    }
}

int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);

    cin >> n >> m;
    adj.resize(n);
    dist.resize(n, INT_MAX);
    parent.resize(n, -1);

    for (int i = 0; i < m; i++) {
        int x, y, w;
        cin >> x >> y >> w;
        adj[--x].push_back({--y, w});
    }

    dijkstra(0);

    for (int i = 1; i < n; i++)
        cout << dist[i] << ' ';
    cout << '\n';

    return 0;
}