Cod sursa(job #3228589)

Utilizator FredyLup Lucia Fredy Data 8 mai 2024 23:27:31
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
// problem statement: https://www.infoarena.ro/problema/dijkstra

#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

constexpr int maxN = 50001;

int n, m;
vector<pair<int, int>> G[maxN];
int path[maxN];

void dijkstra(int source) {
    priority_queue<pair<int, int>> pq;

    for (int i = 1; i <= n; ++i) {
        path[i] = -1;
    }
    path[source] = 0;

    for (auto it : G[source]) {
        pq.push({-it.second, it.first});
    }

    while (!pq.empty()) {
        int node = pq.top().second;
        int distance = -pq.top().first;
        pq.pop();

        if (path[node] != -1) {
            continue;
        }

        path[node] = distance;

        for (const auto& it : G[node]) {
            if (path[it.first] == -1) {
                pq.push({-(distance + it.second), it.first});
            }
        }
    }
}

int main() {
    fin >> n >> m;
    int x, y, w;
    while (m--) {
        fin >> x >> y >> w;
        G[x].push_back({y, w});
    }

    dijkstra(1);

    for (int i = 2; i <= n; ++i) {
        fout << max(path[i], 0) << ' ';
    }

    fin.close();
    fout.close();
    return 0;
}