Cod sursa(job #3335332)

Utilizator anghelmrsmanghel eduard anghelmrsm Data 22 ianuarie 2026 14:09:34
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

struct edge
{
    int j,w;
};

vector <edge> vecini[50001];
bitset <50001> inQueue;
int n, m, dist[50001], cntRelxari[50001];

void BellmanFord (int start)
{
    for (int i=1;i<=n;i++)
        dist[i] = INT_MAX;

    queue <int> q;

    dist[start] = 0;
    q.push(start);
    inQueue[start] = 1;
    cntRelxari[start] = 1;

    while (!q.empty())
    {
        int i = q.front();
        q.pop();
        inQueue[i] = 0;

        for (auto e : vecini[i])
        {
            int j = e.j;
            int w = e.w;

            if (dist[i] + w < dist[j])
            {
                dist[j] = dist[i] + w;

                if (!inQueue[j])
                {
                    q.push(j);
                    inQueue[j] = 1;
                    cntRelxari[j]++;

                    if (cntRelxari[j] > n - 1)
                    {
                        g<<"Ciclu negativ!";
                        return;
                    }
                }
            }
        }
    }
    for (int i=1; i<=n; i++)
        if (i != start)
            g<<dist[i]<<" ";
}

int main()
{
    f>>n>>m;
    for (int i=0; i<m; i++)
    {
        int x, y, w;
        f>>x>>y>>w;
        vecini[x].push_back({y, w});
    }
    BellmanFord(1);
}