Cod sursa(job #3235643)

Utilizator rapidu36Victor Manz rapidu36 Data 19 iunie 2024 16:10:17
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 = 5e4;
const int INF = 6e7;

struct arc
{
    int varf, cost;
};

int d[N+1], nr_in_q[N+1], n, m;
bool in_q[N+1];
vector <arc> a[N+1];
queue <int> q;

bool exista_circuit_negativ()
{
    d[1] = 0;
    q.push(1);
    in_q[1] = true;
    nr_in_q[1] = 1;
    for (int i = 2; i <= n; i++)
    {
        d[i] = INF;
        in_q[i] = false;
        nr_in_q[i] = 0;
    }
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        in_q[x] = false;
        for (auto p: a[x])
        {
            int y = p.varf, c = p.cost;
            if (d[x] + c  < d[y])
            {
                d[y] = d[x] + c;
                if (!in_q[y])
                {
                    q.push(y);
                    in_q[y] = true;
                    nr_in_q[y]++;
                    if (nr_in_q[y] == n)
                    {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

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;
        a[x].push_back((arc){y, c});
    }
    if (exista_circuit_negativ())
    {
        out << "Ciclu negativ!\n";
    }
    else
    {
        for (int i = 2; i <= n; i++)
        {
            out << d[i] << " ";
        }
    }
    in.close();
    out.close();
    return 0;
}