Cod sursa(job #1337790)

Utilizator killlerr1Chilom Mircea killlerr1 Data 9 februarie 2015 15:08:22
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream is("bellmanford.in");
ofstream os("bellmanford.out");

const int INF = 9999;

struct Edge{
    int y, w;
};

vector<vector<Edge> > G;

bool ok;

bool v[50001];

queue<int> Q;

int d[50001];

int n, M;

void Read();
void Write();

void BF(int nod);

int main()
{
    Read();
    BF(1);
    Write();

    is.close();
    os.close();
    return 0;
}

void Read()
{
    is >> n >> M;
    G.resize(n+1);

    int a, b, c;

    while( is >> a >> b >> c )
        G[a].push_back({b, c});

}


void Write()
{
    if( ok == true )
    {
        os << "Ciclu negativ!" << '\n';
        return;
    }

    for( int i = 2; i <= n; ++i )
        os << d[i] << ' ';


}

void BF(int nod)
{
    for( int i = 1; i <= n; ++i )
        d[i] = INF;
    d[nod] = 0;

    Q.push(nod);

    int x;

    while(!Q.empty())
    {
        x = Q.front();
        Q.pop();
        for( const auto& e : G[x] )
            if( d[e.y] > d[x] + e.w )
            {
                if( !v[e.y] )
                {
                    Q.push(e.y);
                    v[e.y] = true;
                }

                d[e.y] = d[x] + e.w;
            }
        for( const auto& e : G[x] )
            if( d[x] + e.w < d[e.y] )
            {
                ok = true;
                return;
            }

    }


}