Cod sursa(job #3341954)

Utilizator ioanabaduIoana Badu ioanabadu Data 21 februarie 2026 22:19:09
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <climits>
#define NMAX 50005
#define EMAX 250005

using namespace std;

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

int nodes, edges, dist[NMAX];

struct edge {
    int x, y, cost;
}arr[EMAX];

void bellmanford (){
    vector <int> dist(nodes+2, INT_MAX);
    dist[1] = 0;

    for (int i=1; i<=nodes; ++i){
        for (int j=0; j<edges; ++j){
            if (dist[arr[j].x] != INT_MAX && dist[arr[j].y] > dist[arr[j].x] + arr[j].cost){
                
                if (i == nodes){
                    out << "Ciclu negativ!";
                    return;
                }
                
                dist[arr[j].y] = dist[arr[j].x] + arr[j].cost;
            }
        }
    }
    
    for (int i=2; i<=nodes; ++i)
        out << dist[i] << ' ';
}

int main (){
    in >> nodes >> edges;
    for (int i=1; i<=edges; ++i)
        in >> arr[i].x >> arr[i].y >> arr[i].cost;

    bellmanford();
    return 0;
}