Cod sursa(job #1337809)

Utilizator killlerr1Chilom Mircea killlerr1 Data 9 februarie 2015 15:23:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 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;

int check[50001];

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 )
    {
        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;
    v[nod] = 1;
    Q.push(nod);

    int x;

    while ( !Q.empty() )
    {
        x = Q.front();
        v[x] = 0;
        Q.pop();
        for ( const auto& e : G[x] )
            if ( d[e.y] > d[x] + e.w )
            {
                d[e.y] = d[x] + e.w;
                if ( !v[e.y] )
                {
                    check[e.y]++;
                    if ( check[e.y] == n )
                    {
                        ok = true;
                        os << "Ciclu negativ!";
                        return;
                    }
                    Q.push(e.y);
                    v[e.y] = 1;
                }

            }
    }

}