Cod sursa(job #3376881)

Utilizator eandrei9Enache Andrei eandrei9 Data 20 noiembrie 2026 09:24:38
Problema Algoritmul Bellman-Ford Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
using namespace std;

struct muchie {
    int x, y, c;
};

const int NMAX = 5e4;
const int MMAX = 250000;
muchie e[MMAX + 1];
int dist[NMAX + 1];

int main() {
    ifstream fin("bellmanford.in");
    ofstream fout("bellmanford.out");

    int n, m;
    fin >> n >> m;

    for (int i = 1; i <= m; i++) {
        fin >> e[i].x >> e[i].y >> e[i].c;
    }

    for (int i = 1; i <= n; i++) {
        dist[i] = 1e9;
    }

    dist[1] = 0;

    for (int i = 1; i <= n - 1; i++) {
        bool updated = false;
        for (int j = 1; j <= m; j++) {
            if (dist[e[j].x] != 1e9 && dist[e[j].y] > dist[e[j].x] + e[j].c) {
                dist[e[j].y] = dist[e[j].x] + e[j].c;
                updated = true;
            }
        }
        if (!updated) {
            break;
        }
    }

    for (int j = 1; j <= m; j++) {
        if (dist[e[j].x] != 1e9 && dist[e[j].y] > dist[e[j].x] + e[j].c) {
            fout << "Ciclu negativ!\n";
            return 0;
        }
    }

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

    fin.close();
    fout.close();
    return 0;
}