Cod sursa(job #3352181)

Utilizator rapidu36Victor Manz rapidu36 Data 24 aprilie 2026 17:34:07
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <queue>
#include <climits>

using namespace std;

const int N = 5e4;

int main() {
    ifstream in("dijkstra.in");
    ofstream out("dijkstra.out");
    int n, m;
    in >> n >> m;
    vector <vector<pair<int, int>>> a(n + 1);
    priority_queue<pair<int, int>, vector <pair <int, int>>, greater<pair<int, int>>> pq;
    for (int i = 0; i < m; i++) {
        int x, y, c;
        in >> x >> y >> c;
        a[x].push_back({c, y});
    }
    in.close();
    vector <int> d(n + 1, INT_MAX);
    vector <bool> in_t(n + 1, false);
    d[1] = 0;
    pq.push({0, 1});
    while (!pq.empty()) {
        int x = pq.top().second;
        int c = pq.top().first;
        pq.pop();
        if (!in_t[x]) {
            in_t[x] = true;
            for (auto p: a[x]) {
                int y = p.second;
                int c = p.first;
                if (d[x] + c < d[y]) {
                    d[y] = d[x] + c;
                    pq.push({d[y], y});
                }
            }
        }
    }
    for (int i = 2; i <= n; i++) {
        if (d[i] == INT_MAX) {
            d[i] = 0;
        }
        out << d[i] << " ";
    }
    out << "\n";
    out.close();
    return 0;
}