Cod sursa(job #3336424)

Utilizator petru-robuRobu Petru petru-robu Data 24 ianuarie 2026 18:14:25
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>
using namespace std;
#define inf INT_MAX

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

struct Edge
{
    int u, v, weight;

    Edge(int u, int v, int weight) : u(u), v(v), weight(weight)
    {
    }

    bool operator<(const Edge &other)
    {
        return weight < other.weight;
    }
};

int n, m, s;
vector<int> dist;
vector<Edge> edge_list;

void read()
{
    fin >> n >> m;
    dist.assign(n + 1, inf);

    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        edge_list.push_back(Edge(x, y, c));
    }
}

void bellmanford()
{
    dist[1] = 0;
    for (int i = 1; i <= n - 1; i++)
    {
        for (auto &e : edge_list)
        {
            if (dist[e.u] + e.weight < dist[e.v])
            {
                dist[e.v] = dist[e.u] + e.weight;
            }
        }
    }
}

bool neg_cycle()
{
    for (auto &e : edge_list)
        if (dist[e.v] > dist[e.u] + e.weight)
            return 1;
    return 0;
}

int main()
{
    read();
    bellmanford();

    if (neg_cycle())
        fout << "Ciclu negativ!\n";
    else
    {
        for (int i = 2; i <= n; i++)
            fout << dist[i] << ' ';
    }
    return 0;
}