Cod sursa(job #2506643)

Utilizator XsoundCristian-Ioan Roman Xsound Data 8 decembrie 2019 16:29:33
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
#define Nmax 50005
using namespace std;

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

struct cv
{
    int node, cost;
};

vector < cv > v[Nmax];
bitset < Nmax > b;
int d[Nmax];

typedef pair < int, int > pi;

int n,m;

void Read ( );

void Dijkstra ( );

int main()
{
    Read ( );

    Dijkstra ( );

    for ( int i = 2; i <= n; i++ )
        fout << d[i] << ' ';

    return 0;
}

void Dijkstra ( )
{
    int lng, node1, node2, distance, cost;

    priority_queue < pi, vector < pi >, greater < pi > > h;

    h.push ( make_pair (0,1) );

    while ( !h.empty() )
    {
        node1= h.top().second;

        if ( b[node1] )
            {
                 h.pop();
                continue;
            }


        else
        {
            b[node1] = 1;

            distance = h.top().first;

            h.pop();

            lng = v[node1].size();

            for ( int i = 0; i < lng; i++ )
            {
                node2 = v[node1][i].node;

                cost = v[node1][i].cost;

                if ( d[node2] == 0 || d[node2] > distance + cost )
                {
                    d[node2] = distance + cost;

                    h.push( make_pair( d[node2], node2 ) );
                }
            }
        }
    }

}

void Read ( )
{
    cv aux;

    int x, y;

    fin >> n >> m;

    for ( int i = 1; i <= m; i++ )
    {
        fin >> x >> y >> aux.cost;

        aux.node = y;

        v[x].push_back(aux);

        aux.node = x;

        v[y].push_back(aux);

    }
}