Pagini recente » Cod sursa (job #100667) | Cod sursa (job #2283684) | Cod sursa (job #1467944) | Cod sursa (job #2926664) | Cod sursa (job #522872)
Cod sursa(job #522872)
/*
* 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], P[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;
if( d[H[k]] <= d[H[son]] )
return;
swap( H[son], H[k] );
P[H[k]]=k;
P[H[son]]=son;
k=son;
}
}
void UpHeap( int k )
{
for( int key=d[H[k]], f=k>>1; k > 1 && d[H[f]] > key; k=f, f>>=1 )
{
swap( H[k], H[f] );
P[H[k]]=k;
P[H[f]]=f;
}
}
inline void Add( int& N, int vertex, int cost )
{
H[++N]=vertex;
P[vertex]=N;
d[vertex]=cost;
UpHeap(N);
}
inline int GetFirst( int& N )
{
int r=H[1];
H[1]=H[N];
P[H[1]]=1;
--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( P[it->y] );
}
}
}
ofstream out( "dijkstra.out" );
copy( d+2, d+N+1, ostream_iterator<int>(out," ") );
out<<'\n';
return 0;
}