Cod sursa(job #2836744)

Utilizator Alle43221Moroz Alexandra-Ioana Alle43221 Data 20 ianuarie 2022 20:41:53
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>
#include <vector>

#define inf 2000000001

using namespace std;

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



struct Muchie
{
    int x, y, cost;
}aux;

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

vector <Muchie> C;

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

    for(int i=1; i<n+1; i++)
    {
        D[i]=inf;
    }

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

   for(int i=0; i<n-1; i++)
   {
       for(auto i: C)
       {
           if(D[i.x]+i.cost<D[i.y])
           {
               D[i.y]=D[i.x]+i.cost;
           }
       }
   }

    for(auto i: C)
       {
           if(D[i.x]+i.cost<D[i.y])
           {
               D[i.y]=D[i.x]+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;
}