Cod sursa(job #3242369)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 11 septembrie 2024 17:33:52
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#include <queue>
#include <cassert>

using namespace std;
using PII = pair<int, int>;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

static constexpr int nMAX = ((int)(5e4) + 4), INF = ((int)(1e9));

int n;
vector<PII> G[nMAX];

auto cmp = [](const PII &x, const PII &y)
{
    if (!(x.first < y.first))
        return 1;
    return 0;
};

priority_queue<PII, vector<PII>, decltype(cmp)> H(cmp);

static void add_edge(const int x, const int y, const int w)
{
    G[x].push_back({w, y});
    return;
}

static void read()
{
    f.tie(nullptr);

    int m = 0;
    f >> n >> m;

    for (int i = 1; i <= m; ++i)
    {
        int u = 0, v = 0, w = 0;
        f >> u >> v >> w;

        add_edge(u, v, w);
    }

    return;
}

int main()
{
    read();

    vector<int> used((n + 1), false), d((n + 1), INF);

    used[1] = true, d[1] = 0;
    for (const PII &it : G[1])
        if (it.first < d[it.second])
            d[it.second] = it.first, H.push(it);

    while (!H.empty())
    {
        while (!H.empty() && used[H.top().second])
            H.pop();

        if (H.empty())
            break;

        int node = H.top().second;
        used[node] = true;
        H.pop();

        for (const PII &it : G[node])
            if (d[node] + it.first < d[it.second])
                assert(!used[it.second]), d[it.second] = (d[node] + it.first), H.push({d[it.second], it.second});
    }

    for (int i = 2; i <= n; ++i)
    {
        g << ((d[i] == INF) ? 0 : d[i]);

        if (i == n)
            g << '\n';
        else
            g << ' ';
    }

    return 0;
}