Cod sursa(job #2693147)

Utilizator CoakazeRotaru Catalin Coakaze Data 4 ianuarie 2021 22:06:30
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

struct muchie
{
    int x;
    int y;
    int val;
};

int d[50005];
vector <muchie> graph;

int main()
{
    ifstream f("bellmanford.in");
    ofstream g("bellmanford.out");
    int n, m;
    f>>n>>m;
    for(int i=0; i<m; i++)
    {
        muchie a;
        f>>a.x>>a.y>>a.val;
        graph.push_back(a);
    }
    for(int i=2; i<=n; i++)
        d[i] = 1001;
    for(int i=0; i<n-1; i++)
        for(auto i : graph)
        {
            if(d[i.x] + i.val < d[i.y])
                d[i.y] = d[i.x] + i.val;
        }
    int ok = 0;
    for(int i=0; i<n-1; i++)
        for(auto i : graph)
        {
            if(d[i.x] + i.val < d[i.y])
                {
                    ok = 1;
                    break;
                }
        }
    if(ok == 1)
        g<<"Ciclu negativ";
    else
        for(int i=2; i<=n; i++)
            g<<d[i]<<" ";
    return 0;
}