Cod sursa(job #3327367)

Utilizator RobertJmekRobert RobertJmek Data 3 decembrie 2025 16:51:23
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

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

int n,m;
vector<pair<int,pair<int,int>>> muchii;
vector<int> dist;
const int INF = 1e9;

void bellman_ford(int n, int m, int start) {
    dist.assign(n + 1, INF);
    dist[start] = 0;
    for ( int i = 1; i<n; i++ ) {
        for ( auto edge : muchii ) {
            int x = edge.first;
            int y = edge.second.first;
            int w = edge.second.second;
            if ( dist[y] > dist[x] + w ) {
                dist[y] = dist[x] + w;
            }
        }
    }
    bool negative_cycle = false;
    for ( auto edge : muchii ) {
            int x = edge.first;
            int y = edge.second.first;
            int w = edge.second.second;
            if ( dist[y] > dist[x] + w ) {
                dist[y] = dist[x] + w;
                negative_cycle = true;
            }
        }
    if ( negative_cycle ) {
        coutt << "Ciclu negativ!\n";
    } else {
        for ( int i = 2; i<=n; i++ ) {
            coutt << dist[i] << " ";
        }
    }
}

int main() {
    cinn >> n >> m;
    for ( int i = 0; i<m; i++ ) {
        int x, y, w;
        cinn >> x >> y >> w;
        muchii.push_back({x, {y, w}});
    }
    bellman_ford(n, m, 1);
    return 0;
}