Cod sursa(job #2755422)

Utilizator Mihai_BarbuMihai Barbu Mihai_Barbu Data 27 mai 2021 10:45:23
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

#define pii pair<int, int>
const int NMAX = 5 * 1e4 + 5;
#define INF (1 << 30)

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

vector<pii> adj[NMAX];
int N, M;

void dijkstra(int src, vector<int>& d) {
    // {d[node], node}
    set<pii> pq;

    d[src] = 0;

    for (auto p : adj[src]) {
        int y = p.first;
        int w = p.second;

        pq.insert({w, y});

        d[y] = w;
    }

    while (!pq.empty()) {
        auto it = pq.begin();

        auto x = (*it).second;

        pq.erase(it);

        for (auto p : adj[x]) {
            int y = p.first;
            int w = p.second;

            if (d[y] > d[x] + w) {
                // delete the previous entry from pq
                pq.erase({d[y], y});

                d[y] = d[x] + w;

                pq.insert({d[y], y});
            }
        }
    }

    for (int x = 1; x <= N; ++x) {
        if (d[x] == INF) {
            d[x] = 0;
        }
    }
}

int main() {
    int i, x, y, w;

    fin >> N >> M;

    for (i = 1; i <= M; ++i) {
        fin >> x >> y >> w;

        adj[x].push_back({y, w});
    }

    vector<int> d(N + 1, INF);
    dijkstra(1, d);

    for (x = 2; x <= N; ++x) {
        fout << d[x] << " ";
    }
    fout << "\n";

    return 0;
}