Cod sursa(job #3335946)

Utilizator petric_mariaPetric Maria petric_maria Data 23 ianuarie 2026 21:50:14
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

const int inf = 1e9 + 7;
int n, m, x, y, c;
bool existsCycle = false;
vector <pair<int, int>> v[50005];
vector <int> d(50005), fr(50005, 0);
priority_queue <pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

void bellman_ford (int val) {
    for (int i=1; i<=n; ++i)
        d[i] = inf;
    d[val] = 0;
    pq.push ({0, val});

    while (!pq.empty()) {
        pair <int, int> k = pq.top();
        pq.pop();

        fr[k.second]++;
        if (fr[k.second] == n) {
            existsCycle = true;
            return;
        }

        if (d[k.second] == k.first) { //sa nu fie o veche intrare in heap
            for (auto x: v[k.second])
            if (d[x.first] > d[k.second] + x.second) {
                d[x.first] = d[k.second] + x.second;
                pq.push ({d[x.first], x.first});
            }
        }
    }
}

int main()
{
    f >> n >> m;
    for (int i=1; i<=m; ++i) {
        f >> x >> y >> c;
        v[x].push_back ({y, c});
    }

    bellman_ford (1);

    if (existsCycle)
        g << "Ciclu negativ!";
    else {
        for (int i=2; i<=n; ++i)
            g << d[i] << ' ';
    }
    return 0;
}