Cod sursa(job #1821083)

Utilizator Tiberiu02Tiberiu Musat Tiberiu02 Data 2 decembrie 2016 16:04:37
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
# include <fstream>
# include <vector>
# include <queue>

using namespace std;

struct path
{
    int dest, cost;

    path( int _dest, int _cost )
    {
        dest = _dest;
        cost = _cost;
    }
};

# define MAX_N 50000
vector<path> v[1 + MAX_N];
bool check[1 + MAX_N];
int dist[1 + MAX_N];

# define undefined 1000000000

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

    ios::sync_with_stdio( false );

    int n, m, i, a, b, c;

    fin >> n >> m;

    for ( i = 0; i < m; i ++ ) {
        fin >> a >> b >> c;
        v[a].push_back( path( b, c ) );
    }

    queue<int> bellman[2];
    bellman[0].push( 1 );

    check[0] = true;
    dist[1] = 0;
    for ( i = 2; i <= n; i ++ )
        dist[i] = undefined;

    for ( i = 0; i <= n; i ++ ) {
        while ( bellman[i & 1].size() ) {
            int t = bellman[i & 1].front();
            bellman[i & 1].pop();
            check[i] = false;

            for ( path p : v[t] )
                if ( p.cost + dist[t] < dist[p.dest] ) {
                    dist[p.dest] = dist[t] + p.cost;
                    if ( !check[p.dest] ) {
                        bellman[i & 1 ^ 1].push( p.dest );
                        check[p.dest] = true;
                    }
                }
        }
    }

    bool negative_cycle = false;
    for ( i = 1; i <= n; i ++ )
        for ( path p : v[i] )
            if ( dist[i] + p.cost < dist[p.dest] )
                negative_cycle = true;

    if ( negative_cycle )
        fout << "Ciclu negativ!";
    else
        for ( i = 2; i <= n; i ++ )
            fout << dist[i] << ' ';

    fin.close();
    fout.close();

    return 0;
}