Cod sursa(job #2718341)

Utilizator Tudor_1808Tudor Ioan Popescu Tudor_1808 Data 8 martie 2021 18:02:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

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

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

int main()
{
    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();
    //initializez d:
    for (int i = 2; i <= n; i++)
    {
        d[i] = INF;
    }
    q.push(1);
    d[1] = 0;
    inq[1] = true;
    nrq[1]++;
    while (!q.empty())
    {
        //scot din q:
        int x = q.front();
        q.pop();
        inq[x] = false;
        //parcurg succesorii lui x:
        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);
                    nrq[y]++;
                    inq[y] = true;
                    if (nrq[y] == n)
                    {
                        out << "Ciclu negativ!";
                        out.close();
                        return 0;
                    }
                }
            }
        }
    }
    for (int i = 2; i <= n; i++)
    {
        if (d[i] != INF)
        {
            out << d[i] << " ";
        }
        else
        {
            out << "0 ";
        }
    }
    out.close();
    return 0;
}