Cod sursa(job #1605994)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 19 februarie 2016 17:54:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include<fstream>
#include<queue>
#include<vector>
#include<cstring>

using namespace std;

ifstream fin( "bellmanford.in" ); ofstream fout( "bellmanford.out" );

struct muchie{
    int x, c;

    muchie() {}
    muchie( int _x, int _c ) : x( _x ), c( _c ) {}
};
typedef vector< muchie > graf;

const int nmax = 5 * 1e4;
const int inf = (1 << 30);
int n;
int d[ nmax + 1 ], modif[ nmax + 1 ];
graf g[ nmax + 1 ];
bool f[ nmax + 1 ];

queue< int > q;

bool bellman_ford() {
    q.push( 1 );
    f[ 1 ] = 1;
    d[ 1 ] = 0;

    while ( !q.empty() ) {
        int i = q.front();
        q.pop();

        for( graf::iterator it = g[ i ].begin(); it != g[ i ].end(); ++ it ) {
            if ( d[ it -> x ] > d[ i ] + (it -> c) ) {
                d[ it -> x ] = d[ i ] + (it -> c);
                ++ modif[ it -> x ];
                if ( modif[ it -> x ] > n ) {
                    return 1;
                }
                if ( f[ it -> x ] == 0 ) {
                    q.push( it -> x );
                    f[ it -> x ] = 1;
                }
            }
        }
        f[ i ] = 0;
    }
    return 0;
}
int main() {
    int m;
    fin >> n >> m;
    for( int i = 0; i < m; ++ i ) {
        int x, y, c;
        fin >> x >> y >> c;
        g[ x ].push_back( muchie( y, c ) );
    }
    for( int i = 1; i <= n; ++ i ) {
        d[ i ] = inf;
    }

    d[ 1 ] = 0;
    if ( bellman_ford() ) {
        fout << "Ciclu negativ!\n";
    } else {
        for( int i = 2; i <= n; ++ i ) {
            fout << d[ i ] << " ";
        }
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}