Cod sursa(job #2837303)

Utilizator DavidMihaiBicu David Mihai DavidMihai Data 22 ianuarie 2022 09:08:45
Problema Algoritmul Bellman-Ford Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#define inf 10000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n,m,cost[5000][5000],d[50001],pred[50001];
bool ok;
void citire()
{
    fin>>n>>m;
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
            if(i==j) cost[i][j]=0;
            else cost[i][j]=inf;

    for(int i=1; i<=m; i++)
    {
        int x,y,c;
        fin>>x>>y>>c;
        cost[x][y]=c;
    }
}
void initializare()
{
    for(int i=2;i<=n;i++)
        {d[i]=inf;
         pred[i]=0;
        }
    d[1]=0;
    pred[1]=0;
}
void BellmanFord()
{
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            for(int k=1;k<=n;k++)
                if(cost[j][k]!=inf && d[k]>d[j]+cost[j][k])
                {
                    d[k]=d[j]+cost[j][k];
                    pred[k]=j;
                }
    ok=true;
    for(int j=1;j<=n;j++)
        for(int k=1;k<=n;k++)
            if(d[k]>d[j]+cost[j][k]) ok=false;
}
/*void afis(int i)
{
    if(pred[i]!=0) afis(pred[i]);
    fout<<i<<' ';
}*/
int main()
{
    citire();
    initializare();
    BellmanFord();
    if(ok)
    for(int i=2;i<=n;i++)
            fout<<d[i]<<' ';
    else fout<<"Circuite negative!";
    return 0;
}