Cod sursa(job #3316124)

Utilizator andreiaramaArama Andrei Robert andreiarama Data 17 octombrie 2025 14:55:27
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstdint>
#include <limits>

using namespace std;

ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");

struct Edge {
    int to;
    int cost;
};

const int MAXN = 50000;
const int INF = numeric_limits<int>::max();

int n, m;
vector<Edge> adj[MAXN + 1];
vector<int> dist(MAXN + 1, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int a, b, c;
        cin >> a >> b >> c;

        adj[a].push_back({b, c});
        adj[b].push_back({a, c});
    }

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

    while (!pq.empty()) {
        int d = pq.top().first;
        int u = pq.top().second;
        pq.pop();

        if (d != dist[u]) continue;

        for (auto &e : adj[u]) {
            if (dist[e.to] > d + e.cost) {
                dist[e.to] = d + e.cost;
                pq.push({dist[e.to], e.to});
            }
        }
    }

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

    return 0;
}