Cod sursa(job #1952638)

Utilizator matystroiaStroia Matei matystroia Data 4 aprilie 2017 11:48:03
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 0.79 kb
#include <fstream>
#include <vector>
using namespace std;

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

struct muchie
{
    int a, b, cost;
};

const int N=5e4+5, INF=2e9;

int n, m, d[N];
vector<muchie> mu;

int main()
{
    fin>>n>>m;
    for(int i=0;i<m;++i)
    {
        int x, y, z;
        fin>>x>>y>>z;
        mu.push_back({x, y, z});
    }

    for(int i=1;i<=n;++i)
        d[i]=INF;

    d[1]=0;
    for(int i=0;i<n-1;++i)
        for(auto mm:mu)
            if(d[mm.a]+mm.cost<d[mm.b])
                d[mm.b]=d[mm.a]+mm.cost;

    for(auto mm:mu)
        if(d[mm.a]+mm.cost<d[mm.b])
        {
            fout<<"Ciclu negativ!";
            return 0;
        }

    for(int i=2;i<=n;++i)
        fout<<d[i]<<" ";

    return 0;
}