Cod sursa(job #1119883)

Utilizator valiro21Valentin Rosca valiro21 Data 24 februarie 2014 20:34:03
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <cstdio>
#include <set>
#include <vector>
#include <map>

#define NMax 50002
#define Inf 1<<30

using namespace std;

long n, m, x, y, z, now;
long cost[NMax];
set<pair<long, long> > q;
vector<pair<long, long> > v[NMax];
bool viz[NMax];

int main ( )
{
    freopen ( "dijkstra.in", "r", stdin );
    freopen ( "dijkstra.out", "w", stdout );

    scanf ( "%ld %ld", &n, &m );
    for ( long i = 1; i <= m; i++ )
        scanf ( "%ld %ld %ld", &x, &y, &z ),
        v[x].push_back ( make_pair ( y, z ) );

    for ( long i = 2; i <= n; i++ )
        cost[i] = Inf;

    cost[1] = 0;
    q.insert ( make_pair( 0, 1 ) );
    while ( !q.empty ( ) ) {
        now = q.begin ( )->second;

        viz[now] = 1;

        for ( long i = 0; i < v[now].size ( ); i++ )
            if ( cost[now] + v[now][i].second < cost[v[now][i].first] )
                cost[v[now][i].first] = cost[now] + v[now][i].second,
                q.insert ( make_pair ( cost[v[now][i].first], v[now][i].first ) );
        q.erase ( q.begin ( ) );
    }

    for ( long i = 2; i <= n; i++ )
        if ( viz[i] ) printf ( "%ld ", cost[i] );
        else printf ( "0 " );

    return 0;
}