Cod sursa(job #459917)

Utilizator BitOneSAlexandru BitOne Data 31 mai 2010 16:20:00
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iterator>
#define Nmax 50111
#define oo 9999999

/*
 *
 */
using namespace std;
typedef pair< int, int > pr;
int N;
int H[Nmax], d[Nmax], P[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] );
        P[H[k]]=k;
        P[H[son]]=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] );
        P[H[k]]=k;
        P[H[f]]=f;
    }
}
inline int pop( void )
{
    int r=H[1];
    P[H[N]]=P[H[1]];
    H[1]=H[N];
    --N;
    DownHeap( 1 );
    return r;
}
inline void push( int k )
{
    H[++N]=k;
    P[k]=N;
    UpHeap( N );
}
int main( void )
{
    int n, 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 ) );
    }
    push( 1 );
    while( N )
    {
        x=pop();
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
        {
            y=it->first, c=it->second;
            if( 0 == P[y] )
            {
                d[y]=d[x]+c;
                push( y );
            }
            else if( d[y] > d[x]+c )
                 {
                     d[y]=d[x]+c;
                     UpHeap( P[y] );
                 }
        }
    }
    ofstream out( "dijkstra.out" );
    copy( d+2, d+n+1, ostream_iterator<int>( out, " " ) );
    out<<'\n';
    return EXIT_SUCCESS;
}