Cod sursa(job #2836818)

Utilizator Alle43221Moroz Alexandra-Ioana Alle43221 Data 20 ianuarie 2022 22:27:19
Problema Algoritmul Bellman-Ford Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define inf 2000000001

using namespace std;

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

queue <int> q;

struct Muchie
{
    int y, cost;
} aux;

int n, m, x, cate;
int D[50001];
bool vf[50001], ok=true;

vector <Muchie> C[50001];

void relaxare(int x)
{
    for(auto i: C[x])
    {
        if(D[x]+i.cost<D[i.y])
        {
            D[i.y]=D[x]+i.cost;
            q.push(i.y);
        }
    }
    cate++;
}

int main()
{
    fin>>n>>m;

    for(int i=0; i<m; i++)
    {
        fin>>x>>aux.y>>aux.cost;
        C[x].push_back(aux);
        if(x==1)
        {
            D[aux.y]=aux.cost;
        }
        else
        {
            D[x]=inf;
        }
    }

    q.push(1);
    while(!q.empty())
    {
        x=q.front();
        q.pop();
        relaxare(x);
    }

    for(auto i: C[1])
    {
        if(D[1]+i.cost<D[i.y])
        {
            D[i.y]=D[1]+i.cost;
            ok=false;
        }
    }

    if(!ok)
    {
        fout<<"Ciclu negativ!";
    }
    else
    {
        for(int i=2; i<=n; i++)
        {
            fout<<D[i]<<' ';
        }
    }

    fin.close();
    fout.close();
    return 0;
}