Cod sursa(job #2970175)

Utilizator Balauta_AlbertBalauta Albert Balauta_Albert Data 24 ianuarie 2023 14:05:44
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
#define N 50005
using namespace std;

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

vector<pair<int, int>> g[N];
queue<int> q;
int viz[N], d[N], nr[N];
int n, m;

void afis(){
    for(int i = 1; i <= n; ++i){
        fout << i << ' ';
        for(auto nod : g[i]){
            fout << nod.first << " " << nod.second;
        }
        fout << '\n';
    }
}

bool bellmanford(){
    for(int i = 1; i <= n; ++i)
        d[i] = INT_MAX;
    d[1] = 0;
    viz[1] = 1;
    q.push(1);
    while(!q.empty()){
        int nod = q.front();
        viz[nod] = 0;
        q.pop();
        for(auto pair : g[nod]){
            int vecin = pair.first;
            int cost = pair.second;
            if(d[nod] + cost < d[vecin]){
                d[vecin] = d[nod] + cost;
                nr[vecin] = nr[nod] + 1;

                if(nr[vecin] > n - 1)
                    return false;

                if(!viz[vecin]){
                    q.push(vecin);
                    viz[vecin] = 1;
                }
            }
        }
    }
    return true;
}

int main() {
    fin >> n >> m;
    for(int i = 0; i < m; ++i) {
        int x, y, z;
        fin >> x >> y >> z;
        g[x].emplace_back(y, z);
    }

    if(bellmanford())
        for(int i = 2; i <= n; ++i)
            if(d[i] != INT_MAX)
                fout << d[i] <<" ";
            else
                fout << 0 << " ";
    else
        fout << "Ciclu negativ!";

    return 0;
}