Cod sursa(job #3300664)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 18 iunie 2025 14:58:20
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

using namespace std;

const int maxN = 50005, inf = 1e9;
int n, m, dist[maxN];
vector <pair <int, int>> G[maxN];
bool used[maxN];

void read() {
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y, c;
        cin >> x >> y >> c;
        G[x].push_back({y, c});
        G[y].push_back({x, c});
    }
}

void dijkstra() {
    priority_queue <pair <int, int>> heap;
    for (int i = 1; i <= n; i++) {
        dist[i] = inf;
    }
    heap.push({0, 1});
    dist[1] = 0;
    while (!heap.empty()) {
        auto [currDist, currNode] = heap.top();
        heap.pop();

        currDist = -currDist;

        if (used[currNode]) {
            continue;
        }
        used[currNode] = 1;

        for (auto [nxtNode, cost] : G[currNode]) {
            if (currDist + cost < dist[nxtNode]) {
                dist[nxtNode] = currDist + cost;
                heap.push({-dist[nxtNode], nxtNode});
            }
        }
    }
}

void print() {
    for (int i = 2; i <= n; i++) {
        if (dist[i] == inf) {
            dist[i] = 0;
        }
        cout << dist[i] << ' ';
    }
}


int main() {
#ifdef LOCAL
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#else
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
#endif
    read();
    dijkstra();
    print();
    return 0;
}