Cod sursa(job #3361895)

Utilizator cont_superscoalaSuperScoala cont_superscoala Data 29 iulie 2026 15:57:47
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
/*
https://infoarena.ro/problema/bellmanford
*/
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int INF = 1e8;

struct arc
{
    int y, c;
};

int main()
{
    ifstream in("bellmanford.in");
    ofstream out("bellmanford.out");
    int n, m;
    in >> n >> m;
    vector <arc> e(m);
    vector <vector <int>> lst_s(n + 1);
    for (int i = 0; i < m; i++)
    {
        int x;
        in >> x >> e[i].y >> e[i].c;
        lst_s[x].push_back(i);
    }
    in.close();
    vector <int> d(n + 1, INF);
    vector <int> nr_q(n + 1, 0);
    vector <bool> in_q(n + 1, false);
    queue <int> q;
    d[1] = 0;
    q.push(1);
    in_q[1] = true;
    nr_q[1]++;
    bool exista_c_n = false;
    while (!q.empty() && !exista_c_n)
    {
        int x = q.front();
        q.pop();
        in_q[x] = false;
        for (auto i: lst_s[x])
        {
            int y = e[i].y, c = e[i].c;
            if (d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                if (!in_q[y])
                {
                    q.push(y);
                    in_q[y] = true;
                    nr_q[y]++;
                    if (nr_q[y] == n)
                    {
                        exista_c_n = true;
                    }
                }
            }
        }
    }

    if (exista_c_n)
    {
        out << "Ciclu negativ!\n";
    }
    else
    {
        for (int x = 2; x <= n; x++)
        {
            out << d[x] << " ";
        }
        out << "\n";
    }
    out.close();
    return 0;
}