Cod sursa(job #3319418)

Utilizator prodsevenStefan Albu prodseven Data 1 noiembrie 2025 12:03:54
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
#include <climits>
#include <bitset>
#include <queue>

using namespace std;

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

int n, m;
vector<vector<pair<int ,int>>> graph;
vector<int> dist;
vector<int> cnt;
queue<int> q;
bitset<(int)(5e4 + 5)> in_queue;

bool spfa() {
    dist[1] = 0;
    q.push(1);
    in_queue[1] = true;
    while (!q.empty()) {
        int current_node = q.front();
        q.pop();
        in_queue[current_node] = false;
        for (auto [neighbour_node, cost] : graph[current_node]) {
            if (dist[current_node] + cost < dist[neighbour_node]) {
                dist[neighbour_node] = dist[current_node] + cost;
                if (!in_queue[neighbour_node]) {
                    q.push(neighbour_node);
                    in_queue[neighbour_node] = true;
                    cnt[neighbour_node]++;
                    if (cnt[neighbour_node] > n) {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

int main() {
    cin >> n >> m;
    dist.resize(n + 2, INT_MAX);
    graph.resize(n + 2);
    cnt.resize(n + 2, 0);
    for (int i = 0 ; i < m ; ++i) {
        int a, b, cost;
        cin >> a >> b >> cost;
        graph[a].push_back({b, cost});
    }
    if (!spfa()) {
        cout << "Ciclu negativ!";
        return 0;
    }
    for (int i = 2 ; i <= n ; ++i) {
        cout << dist[i] << " ";
    }
    return 0;
}