Cod sursa(job #3285899)

Utilizator Vesel_MateiVesel Denis Matei Vesel_Matei Data 13 martie 2025 15:53:03
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
#include <fstream>

using namespace std;

#define INF numeric_limits<int>::max()

struct Edge {
    int to, weight;
};

int n, m, p;
vector<vector<Edge>> g;
vector<int> d;

void dijkstra() {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    d[1] = 0;
    pq.push(make_pair(0, 1));

    while (!pq.empty()) {
        pair<int, int> curr = pq.top();
        pq.pop();

        int dist = curr.first;
        int x = curr.second;

        if (dist > d[x]) continue;

        for (size_t i = 0; i < g[x].size(); i++) {
            int v = g[x][i].to, c = g[x][i].weight;
            if (d[x] + c < d[v]) {
                d[v] = d[x] + c;
                pq.push(make_pair(d[v], v));
            }
        }
    }
}

void read() {
    ifstream fin("dijkstra.in");
    fin >> n >> m ;
    g.resize(n + 1);
    d.assign(n + 1, INF);

    int x, y, z;
    for (int i = 0; i < m; i++) {
        fin >> x >> y >> z;
        g[x].push_back({y, z});
        g[y].push_back({x, z});  // Graph is undirected
    }
    fin.close();
}

void write() {
    ofstream fout("dijkstra.out");
    for (int i = 2; i <= n; i++) {
        if (d[i] == INF)
            fout << "-1 ";
        else
            fout << d[i] << ' ';
    }
    cout << '\n';
    fout.close();
}

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

    read();
    dijkstra();
    write();

    return 0;
}