Cod sursa(job #2896844)

Utilizator mihnea.tTudor Mihnea mihnea.t Data 30 aprilie 2022 23:53:31
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

#define INF ((int)1e9)
#define NMAX ((int)5e4)

using namespace std;

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

struct edge {
    int dest, cost;
};

int n, m;
vector<edge> a[NMAX + 1];
int dist[NMAX + 1];
int pred[NMAX + 1];

bool bellmanford() {
    for (int i = 1; i <= n; ++i) {
        dist[i] = INF;
        pred[i] = -1;
    }

    dist[1] = 0;

    for (int cnt = 1; cnt < n; ++cnt) {
        // Check all edges
        for (int node = 1; node <= n; ++node) {
            for (auto it = a[node].begin(); it != a[node].end(); ++it) {
                edge next = *it;
                if (dist[node] + next.cost < dist[next.dest]) {
                    dist[next.dest] = dist[node] + next.cost;
                    pred[next.dest] = node;
                }
            }
        }
    }

    for (int node = 1; node <= n; ++node) {
        for (auto it = a[node].begin(); it != a[node].end(); ++it) {
            edge next = *it;
            if (dist[node] + next.cost < dist[next.dest]) {
                return false;
            }
        }
    }

    return true;
}

int main(void) {
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int src, dest, cost;
        fin >> src >> dest >> cost;

        a[src].push_back({dest, cost});
    }
    
    if (!bellmanford()) {
        fout << "Ciclu negativ!\n";
        return 0;
    }

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

    fout << "\n";

    return 0;
}