Cod sursa(job #3260484)

Utilizator TonyyAntonie Danoiu Tonyy Data 2 decembrie 2024 16:14:24
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m;
const int Max = 5e4 + 1;
vector<tuple<int,int,int>> edges;
vector<int> d(Max, INT_MAX);

void bellman_ford(int node)
{
    d[node] = 0;
    for(int i = 1; i < n; ++i)
        for(auto j: edges)
            if(d[get<0>(j)] + get<2>(j) < d[get<1>(j)])
                d[get<1>(j)] = d[get<0>(j)] + get<2>(j); 
}

int main()
{
    ios::sync_with_stdio(false);
    fin.tie(NULL);

    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        int x, y, z;
        fin >> x >> y >> z;
        edges.push_back({x, y, z});
    }
    bellman_ford(1);
    for(auto i: edges)
        if(d[get<0>(i)] + get<2>(i) < d[get<1>(i)])
        {
            fout << "Ciclu negativ!";
            return 0;
        }
    for(int i = 2; i <= n; ++i)
        fout << d[i] << " ";

    return 0;
}