Cod sursa(job #435250)

Utilizator alexandru92alexandru alexandru92 Data 7 aprilie 2010 09:18:05
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
/* 
 * File:   main.cpp
 * Author: SpeeDemon
 *
 * Created on April 7, 2010, 9:04 AM
 */
#include <queue>
#include <cstdlib>
#include <fstream>
#include <iterator>
#define oo 0x3f3f3f3f

/*
 * 
 */
using namespace std;
typedef pair< int, int > pr;
queue< int > Q;
vector< int > d, howmuch;
vector< bool > inQ;
vector< vector< pr > > G;
vector< pr >::const_iterator it, iend;
int main(int argc, char** argv)
 {
    int N, M, x, y, c;
    ifstream in( "bellmanford.in" );
    in>>N>>M;
    G.resize(N);
    for( ; M; --M )
    {
        in>>x>>y>>c;
        --x, --y;
        G[x].push_back( pr( y, c ) );
    }
    d.resize( N );
    inQ.resize( N );
    howmuch.resize( N );
    for( Q.push(0); !Q.empty(); )
    {
        x=Q.front(); Q.pop();
        inQ[x]=false;
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
        {
            y=it->first, c=it->second;
            if( !howmuch[y] )
            {
                d[y]=d[x]+c;
                Q.push( y );
                inQ[y]=true;
                ++howmuch[y];
                continue;
            }
            if( d[y] > d[x]+c )
            {
                d[y]=d[x]+c;
                if( !inQ[y] )
                {
                    Q.push(y);
                    inQ[y]=true;
                    ++howmuch[y];
                    if( howmuch[y] > N )
                    {
                        ofstream out( "bellmanford.out" );
                        out<<"Ciclu negativ!\n";
                        return EXIT_SUCCESS;
                    }
                }
            }
        }
    }
    ofstream out( "bellmanford.out" );
    copy( d.begin()+1, d.end(), ostream_iterator<int>( out, " " ) );
    out<<'\n';
    return (EXIT_SUCCESS);
}