Cod sursa(job #2881970)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 31 martie 2022 02:28:20
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>
#define DIM 50005
#define INF 0x3f3f3f3f

using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int n, m, nriq[DIM], d[DIM];
bitset <DIM> iq;
queue <int> q;
vector <pair <int, int>> edges[DIM];

bool bf()
{
    iq[1] = 1;
    nriq[1] = 1;
    q.push(1);
    for (int i = 1; i <= n; i++)
        d[i] = INF;
    d[1] = 0;

    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        iq[node] = 0;

        for (auto child: edges[node])
        {
            int childNode = child.first;
            int cost = child.second;
            if (d[childNode] > d[node] + cost)
            {
                d[childNode] = d[node] + cost;
                if (!iq[childNode])
                {
                    q.push(childNode);
                    iq[childNode] = 1;
                    nriq[childNode]++;
                    if (nriq[childNode] == n)
                        return 0;
                }
            }
        }
    }
    return 1;
}

int main()
{
    f >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        int x, y, cost;
        f >> x >> y >> cost;
        edges[x].push_back(make_pair(y, cost));
    }

    if (!bf())
    {
        g << "Ciclu negativ!";
        return 0;
    }

    for (int i = 2; i <= n; i++)
        g << d[i] << " ";

    return 0;
}