Cod sursa(job #2954725)

Utilizator AleXutzZuDavid Alex Robert AleXutzZu Data 15 decembrie 2022 10:27:35
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>

struct Edge {
    int start = 0, finish = 0, weight = 0;

    Edge(int start, int finish, int weight) {
        this->start = start;
        this->finish = finish;
        this->weight = weight;
    }

    Edge() = default;
};

int main() {
    std::ifstream input("bellmanford.in");
    std::ofstream output("bellmanford.out");

    int n, m;
    std::vector<Edge> edges;
    input >> n >> m;

    for (int i = 0; i < m; ++i) {
        int x, y, t;
        input >> x >> y >> t;
        edges.emplace_back(x, y, t);
    }

    std::vector<int> dist(n + 1, INT32_MAX);
    dist[1] = 0;

    for (int i = 1; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            int u = edges[j].start;
            int v = edges[j].finish;
            int weight = edges[j].weight;
            if (dist[u] != INT32_MAX && dist[v] > dist[u] + weight) dist[v] = dist[u] + weight;
        }
    }

    bool negative_cycle = false;

    for (int j = 0; j < m; ++j) {
        int u = edges[j].start;
        int v = edges[j].finish;
        int weight = edges[j].weight;

        if (dist[u] != INT32_MAX && dist[v] > dist[u] + weight) {
            negative_cycle = true;
            break;
        }
    }

    if (negative_cycle) {
        output << "Ciclu negativ!";
    } else {
        for (int i = 2; i <= n; ++i) output << dist[i] << " ";
    }

    return 0;
}