Cod sursa(job #3325422)

Utilizator temp1234Temp Mail temp1234 Data 25 noiembrie 2025 13:34:32
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 5e4 + 1;
const int inf = 1e9;

vector< pair <int, int> > adj[nmax];
int d[nmax], inq[nmax], cnt[nmax];
int n, m, x, y, c;
queue <int> Q;

int main() {
    fin >> n >> m;
    for(int i = 1; i <= m; i ++) {
        fin >> x >> y >> c;
        adj[x].push_back({y, c});
    }

    for(int i = 1; i <= n; i ++) {
        d[i] = inf;
    }

    inq[1] = 1;
    Q.push(1);
    cnt[1] = 1;
    d[1] = 0;

    while(!Q.empty()) {
        int nod = Q.front();
        Q.pop();
        inq[nod] = 0;
        
        for(auto& v : adj[nod]) {
            int vecin = v.first, cost = v.second;
            if(d[vecin] > d[nod] + cost) {
                d[vecin] = d[nod] + cost;

                if(inq[vecin] == 0){
                    Q.push(vecin);
                    inq[vecin] = 1;
                    cnt[vecin] ++;
                    if(cnt[vecin] > n) {
                        fout << "Ciclu negativ!";
                        return 0;
                    }
                }
            }
        }
    }

    for(int i = 2;i <= n; i ++) {
        fout << d[i] << ' ';
    }
    return 0;
}