Cod sursa(job #2653043)

Utilizator Snake2003lalallalal Snake2003 Data 26 septembrie 2020 18:36:29
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define Nmax 50005

using namespace std;

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

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

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

struct comparaElemente
{
    bool operator() (int a, int b)
    {
        return Distanta[a] > Distanta[b];
    }
};

priority_queue < int, vector < int >, comparaElemente > 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] )
                {
                    Coada.push(Vecin);
                    Vizitat[Vecin] = true;
                }
            }
        }
    }

}


int main()
{
    int vf, muchii;
    fin >> vf >> muchii;
    for(int i = 1; i <= muchii; i ++)
    {
        int x, y, cost;
        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 << Distanta[i] << " ";
        else
            fout << 0 << " ";
    return 0;
}