Cod sursa(job #3165115)

Utilizator octavian202Caracioni Octavian Luca octavian202 Data 5 noiembrie 2023 14:31:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

#define ll long long

using namespace std;

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


const ll NMAX = 50003, INF = 1e14;
int n, m;
ll d[NMAX], inQ[NMAX];
bool vis[NMAX];
vector<pair<ll, ll> > g[NMAX];

bool ford(ll s) {
    for (int i = 1; i <= n; i++) {
        d[i] = INF;
    }
    d[s] = 0;

    queue<ll> q;
    q.push(s);
    bool negativ = false;
    while (!q.empty() && !negativ) {
        ll curr = q.front();
        q.pop();
        vis[curr] = false;

        for (auto nxt : g[curr]) {
            ll nod = nxt.first, cost = nxt.second;
            if (d[nod] > d[curr] + cost) {
                d[nod] = d[curr] + cost;

                if (!vis[nod]) {
                    inQ[nod]++;
                    if (inQ[nod] > n) {
                        negativ = true;
                        break;
                    }

                    vis[nod] = true;
                    q.push(nod);
                }
            }
        }
    }

    return !negativ;
}

int main() {

    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        ll x, y, cost;
        fin >> x >> y >> cost;
        g[x].push_back(make_pair(y, cost));
    }

    if (ford(1)) {
        for (int i = 2; i <= n; i++) {
            fout << d[i] << ' ';
        }
    } else {
        fout << "Ciclu negativ!";
    }


    return 0;
}