Cod sursa(job #3337146)

Utilizator stefanchpStefan Chiper stefanchp Data 26 ianuarie 2026 22:48:57
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;

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

vector <pair<int,int>> g[50005];
vector <int> inq(50005, 0), relax_cnt(50005, 0);
int d[50005], tata[50005];
queue <int> q;

int main()
{
    int n, m;
    int x, y, c;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        g[x].push_back({y, c});
    }
    for(int i = 1; i <= n; i++)
        d[i] = 1e9;
    d[1] = 0;
    tata[1] = -1;
    q.push(1);
    inq[1] = 1;
    bool ciclu_negativ = 0;
    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        inq[1] = 0;
        if(d[nod] == 1e9)
            continue;
        for(int i = 0; i < g[nod].size(); i++)
            if(d[nod] + g[nod][i].second < d[g[nod][i].first])
            {
                relax_cnt[g[nod][i].first]++;
                if(relax_cnt[g[nod][i].first] >= n)
                    ciclu_negativ = 1;
                d[g[nod][i].first] = d[nod] + g[nod][i].second;
                tata[g[nod][i].first] = nod;
                if(inq[g[nod][i].first] == 0)
                    q.push(g[nod][i].first);
            }
    }
    if(ciclu_negativ == 1)
        fout << "Ciclu negativ!";
    else
    {
        for(int i = 2; i <= n; i++)
            fout << d[i] << ' ';
    }
    return 0;
}