Cod sursa(job #3318763)

Utilizator PaulTPaul Tirlisan PaulT Data 28 octombrie 2025 18:45:09
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

using VI = vector<int>;
using PI = pair<int, int>;
using VP = vector<pair<int, int>>;
using VVP = vector<VP>;

constexpr int Inf = 0x3f3f3f3f;
int n, m;
VI d;
VVP G;

void Read();
bool BellmanFord(int x, vector<int>& d);

int main()
{
    Read();
    
    ofstream fout("bellmanford.out");
    if (const bool hasNegativeCycles = BellmanFord(1, d); hasNegativeCycles)
    {
        fout << "Ciclu negativ!";
    }
    else
    {
        for (int i = 2; i <= n; i++)
        {
            fout << d[i] << ' ';
        }
    }
}

void Read()
{
    ifstream fin("bellmanford.in");
    fin >> n >> m;
    G = VVP(n + 1);
    
    int x, y, w;
    for (int i = 0; i < m; ++i)
    {
        fin >> x >> y >> w;
        G[x].emplace_back(y, w);
    }
    fin.close();
}

bool BellmanFord(int x, vector<int>& d)
{
    queue<int> q;
    vector<bool> inQueue(n + 1, false);
    vector<int> cnt(n + 1, 0);
    d = VI(n + 1, Inf);
    
    d[x] = 0;
    q.push(x);
    inQueue[x] = true;
    cnt[x] = 1;
    while (!q.empty())
    {
        x = q.front();
        q.pop();
        inQueue[x] = false;
        
        int y, w;
        for (const auto& edge: G[x])
        {
            y = edge.first;
            w = edge.second;
            if (d[y] > d[x] + w)
            {
                d[y] = d[x] + w;
                if (!inQueue[y])
                {
                    q.push(y);
                    inQueue[y] = true;
                    cnt[y]++;
                    if (cnt[y] >= n)
                        return true;
                }
            }
        }
    }
    
    return false;
}