Pagini recente » Statistici Bianca Floriana (bia423) | Cod sursa (job #2258666) | Cod sursa (job #579983) | Cod sursa (job #3292920) | Cod sursa (job #522868)
Cod sursa(job #522868)
/*
* File: main.cpp
* Author: salexandru
*
* Created on January 16, 2011, 2:23 PM
*/
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#define N_MAX 50011
#define oo 1<<15
using namespace std;
/*
*
*/
struct vertex
{
int y, c;
vertex( int _y=0, int _c=0 ) : y(_y), c(_c) {}
};
bool was[N_MAX];
int H[N_MAX], d[N_MAX];
vector< vertex > G[N_MAX];
vector< vertex >::const_iterator it, iend;
inline void swap( int& x, int& y )
{
int aux=x;
x=y;
y=aux;
}
void DownHeap( int N, int k )
{
for( int son=k<<1; son <= N; son=k<<1 )
{
if( son < N && d[H[son+1]] < d[H[son]] )
++son;
swap( H[son], H[k] );
k=son;
}
}
void UpHeap( int k )
{
for( int key=d[H[k]]; k > 1 && d[H[k>>1]] > key; k>>=1 )
swap( H[k], H[k>>1] );
}
inline void Add( int& N, int vertex, int cost )
{
H[++N]=vertex;
d[vertex]=cost;
UpHeap(N);
}
inline int GetFirst( int& N )
{
int r=H[1];
H[1]=H[N];
--N;
DownHeap( N, 1 );
return r;
}
int main(int argc, char** argv)
{
int N, M, x, y, c, lHeap=1;
ifstream in( "dijkstra.in" );
for( in>>N>>M; M; --M )
{
in>>x>>y>>c;
G[x].push_back( vertex( y, c ) );
}
H[1]=1;
while( lHeap )
{
x=GetFirst(lHeap);
for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
{
if( false == was[it->y] )
{
was[it->y]=true;
Add( lHeap, it->y, it->c+d[x] );
continue;
}
if( it->c+d[x] < d[it->y] )
{
d[it->y]=it->c+d[x];
UpHeap( it->y );
}
}
}
ofstream out( "dijkstra.out" );
copy( d+2, d+N+1, ostream_iterator<int>(out," ") );
out<<'\n';
return 0;
}