Cod sursa(job #3039688)

Utilizator sims_glAlexandru Simion sims_gl Data 28 martie 2023 19:35:08
Problema Algoritmul Bellman-Ford Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include<iostream>
#include<fstream>
#include<set>
#include<algorithm>
#include<vector>
#define inf 1e9
using namespace std;
int i, n, m, x, y, cost, d[50005], ok=1;
struct muchie
{
    int x;
    int y;
    int cost;
};
muchie muc[250005];
int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    cin >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        cin >> x >> y >> cost;
        muchie aux;
        aux.x = x;
        aux.y = y;
        aux.cost = cost;
        muc[i] = aux;
    }
    fill(d + 2, d + n + 1, inf);
    for(int i = 1; i <= n&& ok; i++)
    {
        ok =0;
        for(int j = 1; j <= m; j++)
        {
            int x = muc[j].x;
            int y = muc[j].y;
            int cost = muc[j].cost;
            if(d[y] > d[x] + cost){
            d[y] = min(d[y], d[x] + cost);
            ok=1;
            }
        }
    }
    for(int j = 1; j <= m; j++)
    {
        int x = muc[j].x;
        int y = muc[j].y;
        int cost = muc[j].cost;
        if(d[y] > d[x] + cost)
        {
            cout << "Ciclu negativ!";
            return 0;
        }
    }
    for(int i = 2; i <= n; i++)
    {
        if(d[i] == inf)
            cout << 0 << " ";
        else
            cout << d[i] << " ";
    }

}