Cod sursa(job #3342416)

Utilizator Alexbora13Bora Ioan Alexandru Alexbora13 Data 24 februarie 2026 10:08:28
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;

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

const int NMAX = 50000;

int n, x, y, cost, m;
int dist[NMAX+1];
vector < pair<int,int> > v[NMAX+1];
int inq[NMAX+1];
int viz[NMAX+1];

int main()
{
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        fin >> x >> y >> cost;
        v[x].push_back(make_pair(y,cost));
    }

    dist[1] = 0;
    for(int i=2; i<=n; i++)
        dist[i] = INT_MAX;

    queue <int> q;
    q.push(1);
    inq[1] = 1;
    viz[1] = 1;
    while(!q.empty())
    {
        int nod = q.front();
        viz[nod] = 0;
        q.pop();
        for(auto a : v[nod])
        {
            if(dist[a.first] > dist[nod] + a.second)
            {
                dist[a.first] = dist[nod] + a.second;
                if(viz[a.first] == 0)
                {
                    inq[a.first]++;
                    if(inq[a.first] > n){fout << "Ciclu negativ!";return 0;}
                    viz[nod] = 1;
                    q.push(a.first);
                }
            }
        }
    }   
    for(int i=2; i<=n; i++)
        fout << dist[i] << ' ';
    return 0;
}