Cod sursa(job #3376278)

Utilizator ungureanubogdanUngureanu Bogdan ungureanubogdan Data 17 noiembrie 2026 11:00:33
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <vector>
#include <queue>

std::ifstream cin("bellmanford.in");
std::ofstream cout("bellmanford.out");

struct muchie_t {
    int x, y, cost;
};

int n, m;
std::vector<muchie_t> muchii;
int d[100001];

bool bellman_ford() {
    for(int i = 1; i <= n; ++i) d[i] = 1e9;
    int source = 1;
    d[source] = 0;

    for(int i = 1; i <= n - 1; ++i) {
        for(int j = 0; j < m; ++j) {
            auto M = muchii[j];
            d[M.y] = std::min(d[M.y], d[M.x] + M.cost);
        }
    }

    for(int j = 0; j < m; ++j) {
        auto M = muchii[j];
        if(d[M.x] + M.cost < d[M.y]) {
            return false;
        } 
    }

    return true;
}

int main() {
    cin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        int x, y, cost;
        cin >> x >> y >> cost;
        muchii.push_back({x, y, cost});
    }    

    if(bellman_ford()) {
        for(int i = 2; i <= n; ++i) {
            cout << d[i] << ' ';
        }
    }
    else {
        cout << "Ciclu negativ!";
    }

    return 0;
}