Cod sursa(job #3369351)

Utilizator TeddyDinutaDinuta Eduard Stefan TeddyDinuta Data 19 octombrie 2026 21:53:09
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

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


int main() {
    int n, m;
    in >> n >> m;

    std::vector<std::vector<std::pair<int, int>>> adj(n, std::vector<std::pair<int, int>>());

    for (int i = 0; i < m; i++) {
        int x, y, c;
        in >> x >> y >> c;
        x--;
        y--;
        adj[x].push_back({c, y});
    }

    std::vector<bool> inq(n, false);
    std::vector<int> cnt(n, 0);
    std::vector<int> dp(n, 1e9);

    std::queue<int> q;
    q.push(0);
    dp[0] = 0;
    inq[0] = true;


    while (!q.empty()) {
        int node = q.front();
        q.pop();

        inq[node] = false;

        for (auto it :adj[node]) {
            if (dp[it.second] > dp[node] + it.first) {
                dp[it.second] = dp[node] + it.first;
                cnt[it.second]++;

                if (cnt[it.second] == n + 1) {
                    out << "Ciclu negativ!\n";
                    return 0;
                }

                if (!inq[it.second]) {
                    q.push(it.second);
                    inq[it.second] = true;
                }
            }
        }
    }

    for (int i = 1; i < n; i++)
        out << dp[i] << " ";
}