Cod sursa(job #2352254)

Utilizator CryshanaGanea Carina Cryshana Data 23 februarie 2019 10:19:01
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream in ("dijkstra.in");
ofstream out ("dijkstra.out");
const int INF = 999999999, N = 50001;
bool sel[N];
vector < pair <int, int> > a[N];
priority_queue < pair<int, int> > h;
int d[N], n, m;

void dijkstra ( int x0 )
{
    for ( int i = 1; i <= n; i++ )
    {
        d[i] = INF;
    }
    h = priority_queue <pair<int, int> >();
    d[x0] = 0;
    h.push(make_pair(-d[x0], x0));
    while ( !h.empty() )
    {
        while ( !h.empty() && sel[h.top().second])
        {
            h.pop();
        }
        if ( h.empty())
        {
            return;
        }
        int x = h.top().second;
        sel[x] = true;
        for ( auto p : a[x] )
        {
            int c = p.first, y = p.second;
            if ( d[x] + c < d[y] )
            {
                d[y] = d[x] + c;
                h.push( make_pair ( -d[y], y));
            }
        }
    }
}

int main ()
{
    in >> n >> m;
    for ( int i = 0; i < m; i++ )
    {
        int x, y, c;
        in >> x >> y >> c;
        a[x].push_back(make_pair(c, y));
    }
    dijkstra(1);
    for ( int i = 2; i <= n; i++ )
    {
        if ( d[i] == INF )
        {
            out << "0" << " ";
        }
        else
        {
            out << d[i] << " ";
        }
    }
    return 0;
}