Cod sursa(job #3358385)

Utilizator NFJJuniorIancu Ivasciuc NFJJunior Data 16 iunie 2026 16:31:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
// Belmann-Ford Algorithm
//
// Given a graph where all edges have a (possibly negative) weight, compute the
// shortest distances from a given source vertex s to all other vertices.
//
// Idea: Do N - 1 rounds of relaxations. After these rounds, every node will
// store the stortest path to the starting node.
//
// Shortest Path Faster Algorithm (SPFA)
// - faster algorithm on average
// - keep a queue of nodes that can be relaxed; perform relaxations until you
// can't
//
// Complexity: O(N * M)

#include <bits/stdc++.h>
using namespace std;

int n, m;
vector<vector<pair<int, int>>> adj;
vector<int> parent;
vector<int> dist;

bool spfa(int start)
{
    queue<int> q;
    vector<int> relaxed(n, 0);
    vector<int> inqueue(n, false);

    dist[start] = 0;
    inqueue[start] = true;
    q.push(start);

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        inqueue[node] = false;

        for (auto [next, weight] : adj[node]) {
            int next_dist = dist[node] + weight;
            if (next_dist < dist[next]) {
                parent[next] = node;
                dist[next] = next_dist;

                if (!inqueue[next]) {
                    if (++relaxed[next] >= n)
                        return false; // Negative cycle found
                    inqueue[next] = true;
                    q.push(next);
                }
            }
        }
    }

    return true;
}

int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);

    cin >> n >> m;
    adj.resize(n);
    parent.resize(n, -1);
    dist.resize(n, INT_MAX);

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

    if (!spfa(0)) {
        cout << "Ciclu negativ!\n";
        return 0;
    }

    for (int i = 1; i < n; i++)
        cout << dist[i] << ' ';
    cout << '\n';

    return 0;
}