Cod sursa(job #3336459)

Utilizator theshadowcodertheshadowcoder theshadowcoder Data 24 ianuarie 2026 19:07:02
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin("djikstra.in");
ofstream fout("djikstra.out");

const int MAX_N = 5e4;
const int INF = 1e9;

int n, m;

int min_dist[MAX_N];

vector<pair<int, int>> v[MAX_N];

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

void djikstra() {
    min_dist[0] = 0;
    for (int i = 1; i < n; ++i) {
        min_dist[i] = INF;
    }
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int, int>>> pq;
    pq.push({0, 0});
    while (!pq.empty()) {
        auto [current_distance, current_node] = pq.top();
        pq.pop();
        if (current_distance > min_dist[current_node]) {
            continue;
        }
        for (auto [next_node, cost] : v[current_node]) {
            if (min_dist[current_node] + cost < min_dist[next_node]) {
                min_dist[next_node] = min_dist[current_node] + cost;
                pq.push({min_dist[next_node], next_node});
            }
        }
    }
}

void write() {
    for (int i = 1; i < n; ++i) {
        fout << min_dist[i] << ' ';
    }
    fout << '\n';
}

int main() {
    read();
    djikstra();
    write();
    return 0;
}