Cod sursa(job #3342923)

Utilizator bogdan1479Luca Bogdan Alexandru bogdan1479 Data 26 februarie 2026 10:28:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
const int NMAX = 50001, INF = 1 << 29;

struct muchie {
    int y, w;
};

int N, M;

bool inQ[NMAX];

int D[NMAX], nrViz[NMAX];

vector<muchie> G[NMAX];
queue<int> Q;

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

void citire() {
    int x, y, w;
    fin >> N >> M;

    for(int i = 1; i <= M; ++i) {
        fin >> x >> y >> w;
        G[x].push_back({y, w});
    }
}

void init(int nod) {
    for(int i = 1; i <= N; i++)
        D[i] = INF;
    D[nod] = 0;
}

bool BellmanFord(int nod) {
    int crt, dest, cost;

    init(nod);
    Q.push(nod);
    inQ[nod] = 1;

    while(!Q.empty()) {
        crt = Q.front();
        Q.pop();
        inQ[crt] = 0;

        for(muchie &m : G[crt]) {
            cost = D[crt] + m.w;
            dest = m.y;

            if(cost < D[dest]) {
                D[dest] = cost;

                if(inQ[dest] == 0) {
                    Q.push(dest);
                    inQ[dest] = 1;
                    nrViz[dest]++;

                    if(nrViz[dest] >= N) {
                        return 0; /// Ciclu negativ
                    }
                }
            }
        }
    }

    return 1;
}

int main() {
    citire();

    if(BellmanFord(1)) {
        for(int i = 2; i <= N; i++) {
            fout << D[i] << ' ';
        }
    } else {
        fout << "Ciclu negativ!";
    }

    return 0;
}