Pagini recente » Cod sursa (job #680118) | Cod sursa (job #2102108) | Cod sursa (job #882397) | Cod sursa (job #218297) | Cod sursa (job #558094)
Cod sursa(job #558094)
#include <queue>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#define N_MAX 50011
#define oo 1<<28
#define pr pair< int, int >
using namespace std;
bool was[N_MAX];
int _count[N_MAX], d[N_MAX];
queue< int > Q;
vector< pr > G[N_MAX];
vector< pr >::const_iterator it, iend;
int main()
{
int N, M, x, y, c;
ifstream in( "bellmanford.in" );
for( in>>N>>M; M; --M )
{
in>>x>>y>>c;
d[x]=d[y]=oo;
G[x].push_back( pr( y, c ) );
}
d[1]=0;
for( Q.push(1); !Q.empty(); )
{
x=Q.front(); Q.pop();
was[x]=false;
for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
if( d[it->first] > d[x]+it->second )
{
d[it->first]=d[x]+it->second;
if( false == was[it->first] )
{
was[it->first]=true;
++_count[it->first];
if( _count[it->first] >= N )
{
ofstream out( "bellmanford.out" );
out<<"Ciclu negativ!\n";
return EXIT_SUCCESS;
}
Q.push( it->first );
}
}
}
ofstream out( "bellmanford.out" );
copy( d+2, d+N+1, ostream_iterator<int>( out, " " ) );
out<<'\n';
return EXIT_SUCCESS;
}