Cod sursa(job #3380918)

Utilizator valexandreiValeanu Alexandru-Andrei valexandrei Data 3 decembrie 2026 10:36:33
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>
using namespace std;
int main() {
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    int n, m;
    scanf("%d %d", &n, &m);
    vector<vector<pair<int,int>>> g(n + 1);
    for (int i = 0; i < m; i++) {
        int a, b, c;
        scanf("%d %d %d", &a, &b, &c);
        g[a].push_back({b, c});
    }
    const int INF = INT_MAX;
    vector<int> d(n + 1, INF);
    d[1] = 0;
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;
    pq.push({0, 1});
    while (!pq.empty()) {
        auto [dist, u] = pq.top(); pq.pop();
        if (dist > d[u]) continue;
        for (auto [v, w] : g[u])
            if (dist + w < d[v]) { d[v] = dist + w; pq.push({d[v], v}); }
    }
    for (int i = 2; i <= n; i++) printf("%d ", d[i] == INF ? 0 : d[i]);
    printf("\n");
}