Cod sursa(job #3338823)

Utilizator bogdan6Vieru Bogdan bogdan6 Data 5 februarie 2026 09:46:48
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");


const int NMAX = 50002;
const int INF = 1e9;
struct arc
{
    int vf, c;
};
vector<arc> G[NMAX];
int n,m, start = 1;
int cmin[NMAX];
int nr[NMAX];
bool circuitneg = 0;
queue<int>C;
int main()
{
    int i,x,y,cost;
    arc a;
    //citire
    fin >> n >> m;
    for (int i = 1; i <= n; ++i)
    {
        cmin[i] = INF;
        nr[i] = 0;
    }
    for (int j = 0; j < m; ++j)
    {
        fin >> x >> y >> cost;
        arc a;
        a.vf = y;
        a.c = cost;
        G[x].push_back(a);
    }

    for (int i =1; i<=n; i++) cmin[i] = INF;
    cmin[start] = 0;
    C.push(start);
    while (!C.empty() && !circuitneg)
    {
        x = C.front();
        C.pop();
        {
            for (i = 0; i<G[x].size(); i++)
            {
                y = G[x][i].vf;
                cost = G[x][i].c;
                if(cmin[y] > cmin[x]+cost)
                {
                    cmin[y] = cmin[x] + cost;
                    nr[y]++;
                    if(nr[y] == n) circuitneg = 1;
                    else C.push(y);
                }
            }
        }
    }
    if (circuitneg == 1)
    {
        fout<<"Ciclu negativ!";
    }
    else
    for(int i=2; i<=n; i++)
    {
        fout<<cmin[i]<<' ';
    }
    return 0;
}