Cod sursa(job #2575449)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 6 martie 2020 13:35:39
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>

using namespace std;

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

void usain_bolt()
{
    ios::sync_with_stdio(false);
    fin.tie(0);
}

const int N = 5e4 + 5;

vector < int > d(N, 2e9);
vector < pair < int, int > > a[N];

int f[N];
bool in[N];

void b_f(int k, int n)
{
    queue < int > q;
    d[k] = 0;
    q.push(k);
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        ++f[x];
        if(f[x] == n) {
            fout << "Ciclu negativ!";
            exit(0);
        }
        in[x] = false;
        for(auto v : a[x]) {
            int to = v.first;
            int len = v.second;
            if(d[to] > d[x] + len) {
                d[to] = d[x] + len;
                if(in[to] == false) q.push(to), in[to] = true;
            }
        }
    }
}

int main()
{
    usain_bolt();

    int n, m;

    fin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        int x, y, w;

        fin >> x >> y >> w;
        a[x].push_back({y, w});
    }
    b_f(1, n);
    for(int i = 2; i <= n; ++i) fout << d[i] << " ";
    return 0;
}