Cod sursa(job #3357823)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 15:18:41
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

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

vector<vector<pair<int, int>>> gr(50100);
vector<long long> dist(50100, INT_MAX);
vector<int> cnt(50100, 0);
vector<bool> inQueue(50100, false);
queue<int> Q;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int n, m;
    cin >> n >> m;

    for (int i = 0; i < m; i++) {
        int a, b, val;
        cin >> a >> b >> val;
        gr[a].push_back({b, val});
    }

    dist[1] = 0;
    Q.push(1);
    inQueue[1] = true;

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

        for (auto &edge : gr[node]) {
            int neighbor = edge.first;
            int weight = edge.second;

            if (dist[node] + weight < dist[neighbor]) {
                dist[neighbor] = dist[node] + weight;
                cnt[neighbor] = cnt[node] + 1;

                if (cnt[neighbor] >= n) {
                    cout << "Ciclu negativ!";
                    return 0;
                }

                if (!inQueue[neighbor]) {
                    Q.push(neighbor);
                    inQueue[neighbor] = true;
                }
            }
        }
    }

    for (int i = 2; i <= n; i++) {
        cout << dist[i] << " ";
    }

    return 0;
}