Cod sursa(job #3376860)

Utilizator AlphxByteStefan Alexandru AlphxByte Data 20 noiembrie 2026 08:53:36
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>

const std::string FILE_NAME = "bellmanford";
const int N = 5e4 + 1;
const int INFINIT = 0x3F3F3F3F;

std::ifstream fin(FILE_NAME + ".in");
std::ofstream fout(FILE_NAME + ".out");

struct Edge
{
    int x, y, cost;

    friend std::ifstream& operator >> (std::ifstream&, Edge&);
};

std::ifstream& operator >> (std::ifstream& fin, Edge& edge)
{
    fin >> edge.x >> edge.y >> edge.cost;
    return fin;
}

std::vector<Edge> edges;
int distance[N];
int n;

bool BellmanFord(int start_node)
{
    for (int i = 1; i <= n; i++)
        distance[i] = INFINIT;

    distance[start_node] = 0;
    for (int i = 1; i < n; i++)
        for (const auto& edge : edges)
            if (distance[edge.y] > distance[edge.x] + edge.cost)
                distance[edge.y] = distance[edge.x] + edge.cost;

    for (const auto& edge : edges)
        if (distance[edge.y] > distance[edge.x] + edge.cost)
            return true;

    return false;
}

int main()
{
    int m;
    fin >> n >> m;
    while (m--)
    {
        Edge edge;
        fin >> edge;
        edges.push_back(edge);
    }

    if (BellmanFord(1))
        fout << "Ciclu negativ!";
    else
        for (int i = 2; i <= n; i++)
            fout << distance[i] << ' ';

    return 0;
}