Cod sursa(job #2542437)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 9 februarie 2020 23:27:34
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

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

const int Nmax = 50000, inf = 0x3f3f3f3f;

vector <pair <int, int>> g[Nmax + 5];
queue <int> q;
int n, m, node, other, cost;
int d[Nmax + 5], nrq[Nmax + 5];
bool inq[Nmax + 5];

void Read(){
    fin >> n >> m;
    for (int i = 1; i <= n; i++){
        int x, y, z;
        fin >> x >> y >> z;
        g[x].push_back({y, z});
    }
}

int BellmanFord(){
    memset(d, inf, sizeof d);
    q.push(1);
    d[1] = 0;
    inq[1] = 1;
    nrq[1]++;
    while (!q.empty()){
        node = q.front();
        q.pop();
        for (auto i : g[node]){
            other = i.first;
            cost = i.second;
            if (d[other] > d[node] + cost){
                d[other] = d[node] + cost;
                if (!inq[other]){
                    q.push(other);
                    inq[other] = 1;
                    nrq[other]++;
                    if (nrq[other] > n)
                        return 0;
                }
            }
        }
    }
    return 1;
}

void Print(){
    if (!BellmanFord())
        fout << "Ciclu negativ!";
    else
        for (int i = 2; i <= n; i++)
            fout << d[i] << ' ';
    fout << '\n';
}

int main(){
    Read();
    Print();
    return 0;
}