Cod sursa(job #2899921)

Utilizator Humaru_AndreiHumaru Andrei Humaru_Andrei Data 9 mai 2022 18:27:56
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <queue>
#define NMAX 50004
#define INF 1000000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
void citire();
bool bellman_ford();
void afisare();
bool ok;
struct blford
{
    /* data */
    int x,c;
};
vector <blford> A[NMAX];
queue <int> C;
int cmin[NMAX];
int nr[NMAX];
int n,m;
int main()
{
     citire();
    ok =  bellman_ford();
    afisare();
    return 0;
}
void citire(){ int x,i;
    fin >> n >> m;
    blford poz;
    for (i = 1; i<=m; i++)
    {
        fin >> x >> poz.x >> poz.c;
        A[x].push_back(poz);
    }
}
bool bellman_ford(){int vf,cost;
    int i,y; int x;
    for (i = 1; i<=n; i++)
    cmin[i] = INF;
    cmin[1] = 0;
    nr[1] = 1;
    C.push(1);
    while(!C.empty())
    {
       x = C.front();
       C.pop();
       for (y = 0; y < A[x].size(); y++)
       {
           vf = A[x][y].x; cost = A[x][y].c;
           if (cmin[vf] > cmin[x] + cost)
           {
               cmin[vf] = cmin[x] + cost;
               nr[vf]++;
               C.push(vf);
               if (nr[vf] == n) return 0;
           }
       } 
    }
    return 1;
}
void afisare(){int i;
    if (!ok) fout << "Ciclu Negativ";
    else
    for (i = 2; i<=n; i++)
    fout << cmin[i] << " ";
    fout << '\n';
    }