Cod sursa(job #3371470)

Utilizator arnold23Arnold Tempfli arnold23 Data 30 octombrie 2026 14:57:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <cstdio>
#include <queue>
#include <vector>

using namespace std;

const int MAXN = 50001;
const int INF = 0x3f3f3f3f;

vector<pair<int, int>> g[MAXN];
int dist[MAXN];
int cnt[MAXN];
bool inq[MAXN];

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

    int n, m;
    scanf("%d %d", &n, &m);
    for (int i = 0; i < m; i++) {
        int x, y, c;
        scanf("%d %d %d", &x, &y, &c);
        g[x].push_back(make_pair(y, c));
    }

    for (int i = 1; i <= n; i++) dist[i] = INF;
    dist[1] = 0;

    queue<int> q;
    q.push(1);
    inq[1] = true;

    bool neg = false;
    while (!q.empty() && !neg) {
        int x = q.front();
        q.pop();
        inq[x] = false;

        // A simple path has at most n - 1 edges. Popping a node n times
        // means a reachable negative cycle keeps improving it.
        cnt[x]++;
        if (cnt[x] > n) {
            neg = true;
            break;
        }

        for (int i = 0; i < (int)g[x].size(); i++) {
            int y = g[x][i].first;
            int c = g[x][i].second;
            if (dist[y] > dist[x] + c) {
                dist[y] = dist[x] + c;
                if (!inq[y]) {
                    q.push(y);
                    inq[y] = true;
                }
            }
        }
    }

    if (neg) {
        printf("Ciclu negativ!\n");
        return 0;
    }

    for (int i = 2; i <= n; i++) printf("%d ", dist[i]);
    printf("\n");
    return 0;
}