Cod sursa(job #2466342)

Utilizator Ykm911Ichim Stefan Ykm911 Data 1 octombrie 2019 21:50:09
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>
#include <queue>

using namespace std;

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

const int NMax = 50005;
const int oo = (1 << 30);
int n, m, D[NMax], viz[NMax];

struct CompDist
{
    bool operator ()(int x, int y)
    {
        return D[x] > D[y];
    }
};


vector < pair < int, int > > G[NMax];
priority_queue < int, vector <  int > , CompDist > Q;

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

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

    Q.push(nodStart);
    D[nodStart] = 0;
    viz[nodStart] = 0;

    while(!Q.empty())
    {
        int nodCurent = Q.top();
        Q.pop();
        viz[nodCurent] = 0;

        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(viz[Vecin] == 0)
                {
                    viz[Vecin] = 1;
                    Q.push(Vecin);
                }
            }
        }
    }
}

void Afiseaza()
{
    for(int i = 2; i <= n; i++)
        if(D[i] != oo) fout << D[i] <<" ";
        else fout << "0 ";
}

int main()
{
    Citeste();
    Dijkstra(1);
    Afiseaza();
    return 0;
}