Cod sursa(job #462546)

Utilizator BitOneSAlexandru BitOne Data 11 iunie 2010 14:31:42
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <queue>
#include <cstdlib>
#include <fstream>
#include <iterator>
#define MAX_N 50011
#define oo 1000000000

/*
 *
 */
using namespace std;
typedef pair< int, int > pr;
bool isIn[MAX_N];
int App[MAX_N], d[MAX_N];
queue< int > Q;
vector< pr > G[MAX_N];
vector< pr >::const_iterator it, iend;
int main( void )
{
    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();
        isIn[x]=false;
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
            if( d[x]+it->second < d[it->first] )
            {
                d[it->first]=d[x]+it->second;
                if( false == isIn[it->first] )
                {
                    Q.push(it->first);
                    ++App[it->first];
                    if( App[it->first] >= N )
                    {
                        ofstream out( "bellmanford.out" );
                        out<<"Ciclu negativ!\n";
                        return EXIT_SUCCESS;
                    }
                    isIn[it->first]=true;
                }
            }
    }
    ofstream out( "bellmanford.out" );
    copy( d+2, d+N+1, ostream_iterator<int>( out, " " ) );
    out<<'\n';
    return EXIT_SUCCESS;
}