Cod sursa(job #3335960)

Utilizator and_Turcu Andrei and_ Data 23 ianuarie 2026 22:02:42
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb



#include <bits/stdc++.h>



using namespace std;

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


const int N = 50007;
int n,m;
vector<pair<int, int>> a[N];
vector<int> dist(N, 0), viz(N, 0), updated(N, 0);
bool ciclu_negativ;


void calc_dist()
{
    viz[1] = 1;
    queue<int> q;
    q.push(1);
    viz[1] = 1;

    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        
        for(auto pw : a[x])
        {
            int y = pw.second;
            int c = pw.first;

            if(!viz[y] or dist[y] > dist[x] + c)
            {
                viz[y] = 1;
                dist[y] = c + dist[x];
                updated[y]++;
                q.push(y);

                if(updated[y] == n)
                {
                    ciclu_negativ = 1;
                    return;
                }
            }
        }

    }
}

int main()
{

    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        a[x].push_back({c, y});
    }

    calc_dist();

    if(ciclu_negativ)
        fout << "Ciclu negativ!" ;
    else 
        for (int i = 2; i <= n; i++)
                fout << dist[i] << " ";

    return 0;
}