Cod sursa(job #2659916)

Utilizator Snake2003lalallalal Snake2003 Data 17 octombrie 2020 19:42:23
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

#define Nmax 50005

using namespace std;

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

int Distanta[Nmax];
bool Vizitat[Nmax];

int vf, muchii, x, y, cost;

vector < pair < int, int > > Numbers[Nmax];

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

void Dijkstra( int Nod_Start )
{
    int Nod, Vecin, Cost;

    Coada.push(Nod_Start);
    Vizitat[Nod_Start] = true;

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

        Vizitat[Nod] = false;
        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;
                if( !Vizitat[Vecin] )
                {
                    Vizitat[Vecin] = true;
                    Coada.push(Vecin);
                }
            }
        }
    }

}

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

    Distanta[1] = 0;
    for( int i = 2; i <= vf; ++ i )
        Distanta[i] = 1e9;

    Dijkstra(1);

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