Cod sursa(job #2532792)

Utilizator halexandru11Hritcan Alexandru halexandru11 Data 28 ianuarie 2020 12:51:47
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

#define nax 50005
#define inf (1<<30)
#define pb push_back

using namespace std;

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

int D[nax];
bool InCoada[nax];
int n, m;

vector<pair<int, int>> G[nax];
priority_queue<int, vector<int>, greater<int>> Coada;

void Read()
{
    int x, y, cost;
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        f >> x >> y >> cost;
        G[x].pb(make_pair(y, cost));
    }
}

void Dijkstra(int nodStart)
{
    for(int i = 1; i <= n; ++i)
        D[i] = inf;

    D[nodStart] = 0;
    Coada.push(nodStart);
    InCoada[nodStart] = true;

    while(!Coada.empty())
    {
        int nodCurent = Coada.top();
        Coada.pop();
        InCoada[nodCurent] = false;

        for(size_t i = 0; i < G[nodCurent].size(); ++i)
        {
            int Vecin = G[nodCurent][i].first;
            int Cost = G[nodCurent][i].second;
            if(D[nodCurent] + Cost < D[Vecin])
            {
                D[Vecin] = D[nodCurent] + Cost;
                if(!InCoada[Vecin])
                {
                    Coada.push(Vecin);
                    InCoada[Vecin] = true;
                }
            }
        }
    }
}

void Write()
{
    for(int i = 2; i <= n; ++i)
    {
        if(D[i] != inf)
            g << D[i] << " ";
        else
            g << "0 ";
    }
}

int main()
{
    ios::sync_with_stdio(false);
    Read();
    Dijkstra(1);
    Write();
    return 0;
}