Cod sursa(job #2734886)

Utilizator rares2004Ioan Rares rares2004 Data 1 aprilie 2021 16:20:19
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int N = 50001;
const int INF = 1e9;

vector < pair<int, int>> a[N];
int d[N], nrq[N], n;
bool inq[N];
queue <int> q;

bool bf(int x0)
{
    for (int i = 1; i <= n; i++)
    {
        if (i != x0)
        {
            d[i] = INF;
        }
        else
        {
            d[i] = 0;
        }
    }
    q.push(x0);
    inq[x0] = true;
    nrq[x0]++;
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        inq[x] = false;
        for (auto p: a[x])
        {
            int y = p.first;
            int c = p.second;
            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");
    int m;
    in >> n >> m;
    for (int  i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        a[x].push_back({y, c});
    }
    in.close();
    if (bf(1))
    {
        for (int  i = 2; i <= n; i++)
        {
            out << d[i] << " ";
        }
    }
    else
    {
        out << "Ciclu negativ!";
    }
    out.close();
    return 0;
}