Cod sursa(job #3287884)

Utilizator rapidu36Victor Manz rapidu36 Data 19 martie 2025 16:54:07
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

const int N = 50000;

struct succesor
{
    int vf, cost;
};

int n, m, d[N+1], nrq[N+1];
bool inq[N+1];
vector <succesor> s[N+1];

bool bellman_ford(int x0)
{
    for (int i = 1; i <= n; i++)
    {
        d[i] = INT_MAX;
        inq[i] = false;
        nrq[i] = 0;
    }
    queue <int> q;
    q.push(x0);
    d[x0] = 0;
    inq[x0] = true;
    nrq[x0]++;
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        for (auto p: s[x])
        {
            int y = p.vf;
            int c = p.cost;
            if (d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                if (!inq[y])
                {
                    q.push(y);
                    inq[y] = true;
                    nrq[y]++;
                    if (nrq[y] == n)
                    {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

int main()
{
    ifstream in("bellmanford.in");
    ofstream out("bellmanford.out");
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        s[x].push_back((succesor){y, c});
    }
    if (!bellman_ford(1))
    {
        out << "Ciclu negativ!\n";
    }
    else
    {
        for (int i = 2; i <= n; i++)
        {
            out << d[i] << " ";
        }
        out << "\n";
    }
    in.close();
    out.close();
    return 0;
}