Cod sursa(job #3297401)

Utilizator Arhiva_EducationalaArhiva Educationala Arhiva_Educationala Data 22 mai 2025 16:18:31
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 50000;
const int INF = 1e9;

int minDist[NMAX + 1];

vector <pair<int, int>> edges[NMAX + 1];

bool inQ[NMAX + 1];
int cnt[NMAX + 1];

int main() {
    ifstream fin( "bellmanford.in" );
    ofstream fout( "bellmanford.out" );
    int n, m;
    fin >> n >> m;
    for ( int i = 1, a, b, c; i <= m; i ++ ) {
        fin >> a >> b >> c;
        edges[a].push_back( {b, c} );
    }

    for ( int i = 2; i <= n; i ++ ) {
        minDist[i] = INF;
    }

    queue <int> q;
    q.push( 1 );
    while ( !q.empty() ) {

        int node = q.front();
        q.pop();
        inQ[node] = false;
        for ( auto e : edges[node] ) {
            if ( minDist[node] + e.second < minDist[e.first] ) {
                cnt[e.first] ++;
                if ( cnt[e.first] > n ) {
                    fout << "Ciclu negativ!\n";
                    return 0;
                }
                minDist[e.first] = minDist[node] + e.second;
                if ( !inQ[e.first] ) {
                    q.push( e.first );
                    inQ[e.first] = true;
                }
            }
        }
    }
    for ( int i = 2; i <= n; i ++ ) {
        fout << minDist[i] << ' ';
    }
    fout << '\n';
    return 0;
}