Cod sursa(job #3342591)

Utilizator Alexbora13Bora Ioan Alexandru Alexbora13 Data 24 februarie 2026 20:45:44
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 50000;

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

int main()
{
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        fin >> x  >> y >> cost;
        v[x].push_back(make_pair(y,cost));
    }
    for(int i=2; i<=n; i++)
        dist[i] = INT_MAX;
    dist[1] = 0;
    queue <int> q;
    q.push(1);
    vec[1] = 1;
    inq[1] = 1;
    while(!q.empty())
    {
        int nod = q.front();
        vec[nod] = 0;
        for(auto a : v[nod])
            if(dist[a.first] > dist[nod] + a.second)
            {
                dist[a.first] = dist[nod]+a.second;
                if(!vec[a.first])
                {
                    inq[a.first]++;
                    vec[a.first] = 1;
                    if(inq[a.first] > n)
                    {
                        fout << "Ciclu negativ!";
                        return 0;
                    }
                q.push(a.first);
                }
            }
        q.pop();
    }
    for(int i=2; i<=n; i++)
        fout << dist[i] << ' ';
    return 0;
}