Pagini recente » Cod sursa (job #2716241) | Cod sursa (job #2966515) | Cod sursa (job #826145) | Cod sursa (job #2462984) | Cod sursa (job #1348850)
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
#define INF 0x3f3f3f3f
#define NMAX 50005
#define get_max(a,b) ((a)>(b)?(a):(b))
#define get_min(a,b) ((a)<(b)?(a):(b))
using namespace std;
ifstream in ( "bellmanford.in" );
ofstream out ( "bellmanford.out" );
vector < pair < int ,int > > G[NMAX] ;
queue < pair < int , int > > Bellman;
int used[NMAX] , cost[NMAX] ;
bool inQueue[NMAX];
int N , M ;
bool BellmanFord ( void ){
Bellman.push( make_pair( 1 , 0 ) );
memset ( cost , INF , sizeof(cost));
cost[1] = 0 ;
for ( ; !Bellman.empty(); ){
int node = Bellman.front().first;
int node_cost = Bellman.front().second;
for ( vector < pair < int , int > > ::iterator it = G[node].begin () ; it != G[node].end() ; ++it )
{
if ( node_cost + it->second < cost[it->first])
cost[it->first] = node_cost + it->second ;
++used[it->first];
if ( !inQueue[it->first] ) Bellman.push(make_pair(it->first , cost[it->first])) ;
if( used[it->first] >= N )
{
return 0 ;
}
}
}
return 1;
}
int main ( void ){
int i , j ;
in >> N >> M ;
for ( i = 1 ; i <= M ; ++i ){
int x , y;
in >> x >> y;
G[x].push_back(make_pair( y , x)) ;
}
if ( BellmanFord() ) {
for ( i = 2 ; i <= N ; ++i )
out << cost[i] << " ";
}
else out << "Ciclu negativ!";
return 0 ;
}