Cod sursa(job #2717113)

Utilizator iancupoppPopp Iancu Alexandru iancupopp Data 6 martie 2021 13:56:28
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>

using namespace std;

const int N = 5e4;
const int M = 25e4;
const int INF = 1 << 30;

pair<int, int> edges[M];
int cost[M], d[N + 1];

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

    int n, m, x, y, dist;
    in >> n >> m;
    for (int i = 0; i < m; ++i) {
        in >> x >> y >> dist;
        edges[i] = { x, y };
        cost[i] = dist;
    }
    for (int i = 2; i <= n; ++i)
        d[i] = INF;
    for (int i = 0; i < n - 1; ++i)
        for (int j = 0; j < m; ++j)
            if (d[edges[j].first] + cost[j] < d[edges[j].second])
                d[edges[j].second] = d[edges[j].first] + cost[j];
    bool ok = true;
    for (int i = 0; i < m; ++i)
        if (d[edges[i].first] + cost[i] < d[edges[i].second]) {
            ok = false;
            break;
        }
    if (ok)
        for (int i = 2; i <= n; ++i)
            out << d[i] << ' ';
    else
        out << "Ciclu negativ!";

    in.close();
    out.close();
    return 0;
}