Cod sursa(job #2676472)

Utilizator Snake2003lalallalal Snake2003 Data 24 noiembrie 2020 13:53:37
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define PAIR pair < int, int >
#define Nmax 50005

using namespace std;

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

int vf, muchii, x, y, cost;

vector < PAIR > Numbers[Nmax];

priority_queue < PAIR, vector < PAIR >, greater < PAIR > > Coada;

int Distanta[Nmax];

void Dijkstra( int Nod_S )
{
    int Nod, Vecin, Cost, Dist;

    Coada.push({0, Nod_S});

    while( !Coada.empty() )
    {
        Nod = Coada.top().second;
        Dist = Coada.top().first;
        Coada.pop();

        if( Dist > Distanta[Nod] )
            continue;
        for( unsigned int i = 0; i < Numbers[Nod].size(); ++ i )
        {
            Vecin = Numbers[Nod][i].first;
            Cost = Numbers[Nod][i].second;

            if( Distanta[Nod] + Cost < Distanta[Vecin] )
            {
                Distanta[Vecin] = Distanta[Nod] + Cost;
                Coada.push({Distanta[Vecin], Vecin});
            }

        }
    }

}

int main()
{
    fin >> vf >> muchii;
    for( int i = 1; i <= muchii; ++ i )
    {
        fin >> x >> y >> cost;
        Numbers[x].push_back({y, cost});
    }
    for( int i = 2; i <= vf; ++ i )
        Distanta[i] = 1e9;
    Distanta[1] = 0;

    Dijkstra(1);

    for( int i = 2; i <= vf; ++ i )
        if( Distanta[i] != 1e9 )
            fout << Distanta[i] << " ";
        else
            fout << 0 << " ";
    return 0;
}