Cod sursa(job #3278303)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 19 februarie 2025 10:25:42
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>

using namespace std;

int main() {

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

    const int INF = 1e9;

    int n, m;
    in >> n >> m;

    vector<vector<pair<int, int>>> g(n + 1);
    for(int i = 1; i <= m; i++) {
        int x, y, c;
        in >> x >> y >> c;
        g[x].push_back({y, c});
    }  

    vector<int> dist(n + 1, INF);
    dist[1] = 0;
    for(int t = 1; t < n; t++) {
        for(int node = 1; node <= n; node++) {
            for(auto [son, w] : g[node]) {
                dist[son] = min(dist[son], dist[node] + w);
            }
        }
    }
    bool negativeCycle = false;
    for(int node = 1; node <= n; node++) {
        for(auto [son, w] : g[node]) {
            if(dist[node] + w < dist[son]) {
                negativeCycle = true;
                break;
            }
        }
    }

    if(negativeCycle) {
        out << "Ciclu negativ!";
    } else {
        for(int i = 2; i <= n; i++) {
            out << dist[i] << ' ';
        }
        out << '\n';
    }


    return 0;
}