Cod sursa(job #2049763)

Utilizator AlexAxeToporan Victor AlexAxe Data 27 octombrie 2017 17:06:58
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <algorithm>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in(" bellmanford.in");
ofstream out(" bellmanford.out");

const int NMax = 50000 + 2, oo = 2000000000;
int N, M, D[NMax];
vector <pair <int, int> > G[NMax];
bool Cycle;

void Citire (){
    in >> N >> M;
    int x, y, k;
    for (int i = 1; i <= M; i++){
        in >> x >> y >> k;
        G[x].push_back(make_pair(y, k));
    }
}

void Bellmanford(){
    for (int i = 2; i <= N; i++)
        D[i] = oo;
    for (int k = 1; k <= N; k++){
        for (int i = 1; i <= N ; i++)
            for (auto j : G[i]){
                int Vecin = j.first, Cost = j.second;
                D[Vecin] = min (D[Vecin], D[i] + Cost);
            }
    }

    for (int i = 1; i <= N ; i++)
        for (auto j : G[i]){
            int Vecin = j.first, Cost = j.second;
            if(D[Vecin] > D[i] + Cost);
                Cycle = 1;
        }
}

void Afisare (){
    for (int i = 2; i <= N; i++){
        out << D[i] << " ";
    }
}

int main (){
    Citire();
    Bellmanford();
    if (!Cycle)
        out << "Ciclu negativ!";
    else
        Afisare();
    return 0;
}