Pagini recente » Cod sursa (job #177644) | Cod sursa (job #1885286) | Cod sursa (job #965264) | Cod sursa (job #421770) | Cod sursa (job #436150)
Cod sursa(job #436150)
/*
* File: main.cpp
* Author: VirtualDemon
*
* Created on April 7, 2010, 8:19 PM
*/
#include <cstdlib>
#include <fstream>
#include <iterator>
#define Nmax 100001
/*
*
*/
using namespace std;
struct vertex
{
int y, c;
vertex* next;
} *G[Nmax];
int N=1;
int H[Nmax], P[Nmax], D[Nmax];
inline void swap( int& x, int& y )
{
int aux=x;
x=y;
y=aux;
}
inline void add( const int& x, const int& y, const int& c )
{
vertex* q=new vertex;
q->y=y; q->c=c;
q->next=G[x];
G[x]=q;
}
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 void push( int k )
{
H[++N]=k;
P[k]=N;
UpHeap( N );
}
int main(int argc, char** argv)
{
vertex* it;
int n, M, x, y, c;
ifstream in( "dijkstra.in" );
in>>n>>M;
for( ; M; --M )
{
in>>x>>y>>c;
--x, --y;
add( x, y, c );
}
P[0]=1;
while( N )
{
x=pop();
for( it=G[x]; it; it=it->next )
{
y=it->y, c=it->c;
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;
}