Cod sursa(job #2954512)

Utilizator Iordache_CezarIordache Cezar Iordache_Cezar Data 14 decembrie 2022 17:49:43
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>
#define NMAX 50008
#define INF 1e9
#pragma GCC optimize("O3")

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

struct Muchie
{
    int nod, cost;
};

struct comparare
{
    bool operator() (const Muchie & a, const Muchie & b)
    {
        return a.cost > b.cost;
    }
};

int n, m, dp[NMAX];
vector < pair <int, int> > G[NMAX];
priority_queue <Muchie, vector <Muchie>, comparare> H;

void Dijkstra(int start);

int main()
{
    ios_base::sync_with_stdio(0); fin.tie(0);
    int x, y, z;
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y >> z;
        G[x].push_back({y, z});
    }

    for (int i = 0; i <= n; i++)
        dp[i] = INF;

    Dijkstra(1);
    for (int i = 2; i <= n; i++)
    {
        if (dp[i] == INF)
            dp[i] = 0;
        fout << dp[i] << ' ';
    }
    return 0;
}

void Dijkstra(int start)
{
    Muchie M;
    dp[start] = 0;
    H.push({start, dp[start]});

    while (!H.empty())
    {
        M = H.top();
        H.pop();

        if (M.cost > dp[M.nod])
            continue;

        for (auto el : G[M.nod])
        {
            int vecin = el.first;
            int c = el.second;
            if (M.cost + c < dp[vecin])
            {
                dp[vecin] = M.cost + c;
                H.push({vecin, dp[vecin]});
            }
        }

    }
}