Cod sursa(job #3320820)

Utilizator RalucaioneteRalucaIonete Ralucaionete Data 7 noiembrie 2025 14:53:33
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");

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

struct succesor
{
    int vf;
    int c;
};

vector<succesor> ls[N + 1];
queue<int> q;
int n, d[N + 1], nr_in_q[N + 1];
bool in_q[N + 1];

bool bf_moore()
{
    for (int i = 2; i <= n; i++)
        d[i] = INF;

    d[1] = 0;
    q.push(1);
    in_q[1] = true;
    nr_in_q[1]++;

    while (!q.empty())
    {
        int x = q.front();
        q.pop();

        for (auto s : ls[x])
        {
            int y = s.vf;
            int c = s.c;

            if (d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                nr_in_q[y]++;

                if (nr_in_q[y] == n)
                    return false;
                if (!in_q[y])
                    q.push(y);
            }
        }
    }
    return true;
}

int main()
{
    int m;
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        ls[x].push_back((succesor){y, c});
    }
    if (bf_moore())
    {
        for (int i = 2; i <= n; i++)
            cout << d[i] << " ";
    }
    else
    {
        cout << "Ciclu negativ!";
    }
    return 0;
}