Cod sursa(job #3205861)

Utilizator TeddyDinutaDinuta Eduard Stefan TeddyDinuta Data 20 februarie 2024 18:37:30
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
vector<pair<int, int>> v[50005];
int d[50005];
int n, m, x, y, c;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
bool ok[50005];

void dijkstra(int node) {
    q.push({0, node});
    for (int i = 1; i <= n; i++) {
        if (i != node) {
            d[i] = 1e9;
        }
    }

    while (!q.empty()) {
        int x = q.top().second;
        int c = q.top().first;
        q.pop();
        if (ok[x]) {
            continue;
        }
        ok[x] = 1;

        for (auto it : v[x]) {
            if (d[it.first] > c + it.second) {
                d[it.first] = c + it.second;
                q.push({d[it.first], it.first});
            }
        }
    }
}
int main()
{
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    in >> n >> m;
    for (int i = 1; i <= m; i++) {
        in >> x >> y >> c;
        v[x].push_back({y, c});
    }

    dijkstra(1);

    for (int i = 2; i <= n; i++) {
        out << d[i] << " ";
    }
    return 0;
}