Cod sursa(job #2981330)

Utilizator anastasei_tudorAnastasei Tudor anastasei_tudor Data 17 februarie 2023 18:38:38
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
#define NMAX 50008
#define INF 1e9 + 8

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

struct Muchie
{
    int vf, cost;
};

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

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

void Dijkstra(int start);

int main()
{
    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)
{
    dp[start] = 0;
    H.push({start, 0});
    while (!H.empty())
    {
        int vf = H.top().vf;
        int cost = H.top().cost;
        H.pop();

        if (cost > dp[vf])
            continue;

        for (auto el : G[vf])
        {
            if (dp[el.vf] > dp[vf] + el.cost)
            {
                dp[el.vf] = dp[vf] + el.cost;
                H.push({el.vf, dp[el.vf]});
            }
        }
    }
}