Cod sursa(job #3347574)

Utilizator moloDaniMolodet Andrei Daniel moloDani Data 17 martie 2026 12:13:12
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

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

const int mxN = 5e4 + 1;
const int INF = INT_MAX;

struct muchie {
    int vecin, cost;
};

bool operator>(muchie a, muchie b) {
    return a.cost > b.cost;
}

int dist[mxN], n, m;
vector<muchie> G[mxN];
priority_queue<muchie, vector<muchie>, greater<muchie>> Q;

int main() {
    int a, b, c;
    fin >> n >> m;

    // Initialize all distances to infinity
    for (int i = 1; i <= n; i++)
        dist[i] = INF;
    dist[1] = 0;

    for (int i = 1; i <= m; i++) {
        fin >> a >> b >> c;
        G[a].push_back({b, c});
        G[b].push_back({a, c});
    }

    Q.push({1, 0});

    while (!Q.empty()) {
        muchie nod = Q.top();
        Q.pop();

        if (nod.cost > dist[nod.vecin])
            continue;

        for (auto x : G[nod.vecin]) {
            int newDist = dist[nod.vecin] + x.cost;
            if (newDist < dist[x.vecin]) {
                dist[x.vecin] = newDist;
                Q.push({x.vecin, newDist});
            }
        }
    }

    for (int i = 2; i <= n; i++) {
        if (dist[i] == INF)
            fout << 0 << " "; // convention: 0 means unreachable
        else
            fout << dist[i] << " ";
    }
}