Cod sursa(job #447041)

Utilizator alexandru92alexandru alexandru92 Data 27 aprilie 2010 16:30:14
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on April 26, 2010, 8:50 PM
 */
#include <vector>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#define Nmax 50011
#define oo 0x3f3f3f3f

/*
 * 
 */
using namespace std;
typedef pair< int, int > pr;
int N;
int H[Nmax], P[Nmax], d[Nmax];
vector< pr > G[Nmax];
vector< pr >::const_iterator it, iend;
inline void DownHeap( int k )
{
    for( int son=2*k; son <= N; k=son, son*=2 )
    {
        if(  son < N && d[H[son+1]] < d[H[son]] )
            ++son;
        if( d[H[k]] <= d[H[son]] )
            return;
        swap( H[k], H[son] );
        swap( P[H[k]], P[H[son]] );
    }
}
inline void UpHeap( int k )
{
    for( int key=d[H[k]], f=k/2; k > 1 && key < d[H[f]]; k=f, f/=2 )
    {
        swap( H[k], H[f] );
        swap( P[H[k]], P[H[f]] );
    }
}
inline int pop( void )
{
    int r=H[1];
    P[H[1]]=0;
    H[1]=H[N];
    --N;
    DownHeap(1);
    return r;
}
inline void push( int k )
{
    H[++N]=k;
    P[k]=N;
    UpHeap( N );
}
int main(int argc, char** argv)
{
    int M, x, y, c;
    ifstream in( "dijkstra.in" );
    for( in>>N>>M; M; --M )
    {
        in>>x>>y>>c;
        G[x].push_back( pr( y, c ) );
    }
    M=N;
    fill( d+2, d+N+1, oo );
    for( N=0, push(1); N; )
    {
        x=pop();
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
        {
            y=it->first, c=it->second;
            if( d[y] > d[x]+c )
            {
                d[y]=d[x]+c;
                if( !P[y] )
                {
                    push(y);
                }
                else UpHeap( P[y] );
            }
        }
    }
    ofstream out( "dijkstra.out" );
    for( x=2; x <= M; ++x )
        if( oo == d[x] )
            out<<"0 ";
        else out<<d[x]<<' ';
    return (EXIT_SUCCESS);
}