Cod sursa(job #2565434)

Utilizator radugheoRadu Mihai Gheorghe radugheo Data 2 martie 2020 14:14:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin  ("bellmanford.in");
ofstream fout ("bellmanford.out");

int n, m, i, x, y, c, ok;
int f[50005], d[50005], ff[50005];

vector <pair<int, int> > L[50005];

queue <int> q;

void bellman (){
    q.push(1);
    for (int i=2; i<=n; i++){
        d[i] = INT_MAX;
    }
    d[1] = 0;
    f[1] = 1;
    while (!q.empty()){
        int nod = q.front();
        q.pop();
        f[nod] = 0;
        for (int i=0; i<L[nod].size(); i++){
            int vecin = L[nod][i].first;
            int cost  = L[nod][i].second;
            if (d[vecin] > d[nod] + cost){
                d[vecin] = d[nod] + cost;
                ff[vecin]++;
                if (ff[vecin] == n){
                    fout << "Ciclu negativ!";
                    ok = 1;
                    return ;
                }
                if (f[vecin] == 0){
                    q.push(vecin);
                    f[vecin] = 1;
                }
            }
        }
    }
}

int main(){
    fin >> n >> m;
    for (i=1; i<=m; i++){
        fin >> x >> y >> c;
        L[x].push_back({y, c});
    }
    bellman();
    if (!ok){
        for (i=2; i<=n; i++){
            fout << d[i] << " ";
        }
    }
    return 0;
}