Cod sursa(job #3380916)

Utilizator valexandreiValeanu Alexandru-Andrei valexandrei Data 3 decembrie 2026 10:34:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>
using namespace std;
int main() {
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    int n, m;
    scanf("%d %d", &n, &m);
    vector<vector<pair<int,int>>> g(n + 1);
    for (int i = 0; i < m; i++) {
        int x, y, c;
        scanf("%d %d %d", &x, &y, &c);
        g[x].push_back({y, c});
    }
    const int INF = 1e9;
    vector<int> d(n + 1, INF), cnt(n + 1, 0);
    vector<char> inq(n + 1, 0);
    queue<int> q;
    d[1] = 0; q.push(1); inq[1] = 1; cnt[1] = 1;
    while (!q.empty()) {
        int u = q.front(); q.pop(); inq[u] = 0;
        for (auto [v, w] : g[u]) {
            if (d[u] + w < d[v]) {
                d[v] = d[u] + w;
                if (!inq[v]) {
                    if (++cnt[v] >= n) { puts("Ciclu negativ!"); return 0; }
                    inq[v] = 1; q.push(v);
                }
            }
        }
    }
    for (int i = 2; i <= n; i++) printf("%d ", d[i]);
    printf("\n");
}