Pagini recente » Cod sursa (job #214628) | Cod sursa (job #2013537) | Cod sursa (job #2262466) | Cod sursa (job #433331) | Cod sursa (job #435745)
Cod sursa(job #435745)
/*
* File: main.cpp
* Author: VirtualDemon
*
* Created on April 7, 2010, 8:19 PM
*/
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iterator>
#define Nmax 100001
/*
*
*/
using namespace std;
typedef pair< int, int > pr;
int N=1;
int H[Nmax], P[Nmax], D[Nmax];
vector< vector< pr > > G;
vector< pr >::const_iterator it, iend;
inline void swap( int& x, int& y )
{
int aux=x;
x=y;
y=aux;
}
inline void DownHeap( int k )
{
int son;
for( ; ; )
{
son=2*k;
if( son > N )
return;
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]] );
k=son;
}
}
inline void UpHeap( int k )
{
int key=D[H[k]], f=k/2;
while( k > 1 && key < D[H[f]] )
{
swap( H[k], H[f] );
swap( P[H[k]], P[H[f]] );
k=f;
f/=2;
}
}
inline int pop( void )
{
int r=H[1];
P[H[1]]=P[H[N]];
H[1]=H[N];
--N;
DownHeap( 1 );
return r;
}
inline int push( int k )
{
H[++N]=k;
P[k]=N;
UpHeap( N );
}
int main(int argc, char** argv)
{
int n, M, x, y, c;
ifstream in( "dijkstra.in" );
in>>n>>M;
G.resize(n);
for( ; M; --M )
{
in>>x>>y>>c;
--x, --y;
G[x].push_back( pr( y, c ) );
}
P[0]=1;
while( N )
{
x=pop();
for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
{
y=it->first, c=it->second;
if( !P[y] )
{
D[y]=D[x]+c;
push( y );
continue;
}
if( D[y] > D[x]+c )
{
D[y]=D[x]+c;
UpHeap( P[y] );
}
}
}
ofstream out( "dijkstra.out" );
copy( D+1, D+n, ostream_iterator<int>( out, " " ) );
out<<'\n';
return EXIT_SUCCESS;
}