Cod sursa(job #3338800)

Utilizator Furtuna_LucaFurtuna Luca Furtuna_Luca Data 5 februarie 2026 09:29:06
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
#define NMAX 5002
#define INF 1e8

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

struct arc
{
    int x, c;
};

vector <arc> arce[NMAX];
queue <int> q;

bool neg;
int n, m, start = 1;
int cmin[NMAX];
int nr[NMAX];

void citire();
void bellmanford();

int main()
{
    int i;
    citire();
    bellmanford();
    if(neg)
        fout << "Ciclu negativ!";
    else
    {
        for(i = 2; i <= n; i++)
            fout << cmin[i] << ' ';
    }
    return 0;
}

void bellmanford()
{
    int i, vf, cost, x;
    for(i = 1; i <= n; i++)
        cmin[i] = INF;
    cmin[1] = 0;
    q.push(1);
    while(!q.empty() && !neg)
    {
        x = q.front();
        q.pop();
        for(i = 0; i < arce[x].size(); i++)
        {
            vf = arce[x][i].x;
            cost = arce[x][i].c;
            if(cmin[vf] > cmin[x] + cost)
            {
                cmin[vf] = cmin[x] + cost;
                nr[vf]++;
                if(nr[vf] >= n)
                {
                    neg = true;
                    break;
                }
                else
                    q.push(vf);
            }
        }
    }
}

void citire()
{
    arc vf;
    int i, x, y, cost;

    fin >> n >> m;
    for(i = 1; i <= m; i++)
    {
        fin >> x >> y >> cost;
        vf.x = y;
        vf.c = cost;
        arce[x].push_back(vf);
    }
}