Cod sursa(job #2496592)

Utilizator niculaandreiNicula Andrei Bogdan niculaandrei Data 21 noiembrie 2019 09:42:13
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
#define N_MAX 50005

using namespace std;

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

struct Node
{
    int y, c;

    bool operator < (const Node &n) const
    {
        return n.c < c;
    }
};

int n, m, x, y, c;
int D[N_MAX];
vector < Node > G[N_MAX];
priority_queue < Node > PQ;

void Dijkstra()
{
    int currNode = PQ.top().y;
    int currCost = PQ.top().c;
    PQ.pop();
    for (Node node: G[currNode])
        if (D[node.y] == INT_MAX)
        {
            D[node.y] = currCost + node.c;
            PQ.push({node.y, D[node.y]});
        }
    if (PQ.size())
        Dijkstra();
}

int main()
{
    fin >> n >> m;
    for (int i = 2; i <= n; i++)
        D[i] = INT_MAX;
    while (m--)
    {
        fin >> x >> y >> c;
        G[x].push_back({y, c});
    }
    PQ.push({1, 0});
    Dijkstra();
    for (int i = 2; i <= n; i++)
        if (D[i] == INT_MAX)
            fout << "0 ";
        else
            fout << D[i] << " ";
    return 0;
}