Cod sursa(job #2856711)

Utilizator gabrieldima6543DIMA GABI gabrieldima6543 Data 24 februarie 2022 11:38:00
Problema Algoritmul Bellman-Ford Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
#define NMAX 50002
#define INF 1000000002

using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, uz[NMAX], pre[NMAX], cmin[NMAX], x0=1;
int afis[NMAX], nr[NMAX];
queue<int> C;


struct varf
{
    int x;
    int c;
};

vector<varf> G[NMAX]; // liste de adiacenta cu costuri

void citire();
void afisare();
bool bellmanford();
void afisare_drum();



int main()
{
    citire();
    afisare();
    return 0;
}

void citire()
{
    int i, j, c;
    varf aux;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>i>>j>>c;
        aux.x=j;
        aux.c=c;
        G[i].push_back(aux);
    }
    for(i=1; i<=n; i++)
        cmin[i]=INF;
    cmin[x0]=0;
}

bool bellmanford() //returneaza 0 daca exista circuite de cost negativ si 1 astfel
{
    int i, vf, x, cost;
    //initializez coada cu vf de start
    C.push(x0);
    nr[x0]=1;
    while(!C.empty())
    {
        x=C.front();
        C.pop();
        //parcurg lista de adiacenta a lui x
        for(i=0; i<G[x].size(); i++)
        {
             vf=G[x][i].x;
             cost=G[x][i].c;
             if(cmin[vf]>cmin[x]+cost)
             {
                cmin[vf]=cmin[x]+cost;
                C.push(vf);
                nr[vf]++;
                if(nr[vf]==n)
                    return 0;
             }
        }
    }
    return 1;
}

void afisare()
{
    int i;
    if(bellmanford()==0) fout<<"Ciclu negativ!";
        else
        for(i=2; i<=n; i++)
            fout<<cmin[i]<<' ';

}