Cod sursa(job #1348965)

Utilizator superman_01Avramescu Cristian superman_01 Data 19 februarie 2015 22:01:18
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <iostream>
#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 <  int  > Bellman;
int used[NMAX] , cost[NMAX] ;
bool inQueue[NMAX];
int N , M ;

bool BellmanFord ( void ){
   Bellman.push(  1 );
   memset ( cost , INF , sizeof(cost));
   cost[1] = 0 ;
   for ( ; Bellman.size(); ){
     int node = Bellman.front();
     Bellman.pop();
     inQueue[node] = false;
     for ( vector < pair < int , int > > ::iterator it = G[node].begin () ; it != G[node].end() ; ++it )
          if ( cost[node]+ it->second < cost[it->first])
       {
           cost[it->first] = cost[node] + it->second ;
           ++used[it->first];
        if ( !inQueue[it->first] ) Bellman.push( it->first ) , inQueue[it->first] = true;
        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 , macost;
           in >> x >> y >> macost;
           G[x].push_back(make_pair( y , macost )) ;
       }
    if (  BellmanFord() ) {

       for ( i = 2 ; i <= N ; ++i )
                out << cost[i] << " ";
    }
    else out << "Ciclu negativ!";
   return 0 ;
}