Cod sursa(job #3286371)

Utilizator CaldareaCiprianCaldarea Ciprian CaldareaCiprian Data 14 martie 2025 09:21:53
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <tuple>
#include <queue>

using namespace std;


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

using VI = vector<int>;
using VPI = vector<pair<int, int>>;
using VVPI = vector<VPI>;
using VVI = vector<VI>;
using VB = vector<bool>;


int n, m;
const int INF = (1 << 30);

VVPI G;
VI v;
VI d;
bool cicluNegativ;

void BellmanFord(int x)
{
    queue<int> Q;
    VB inQ(n + 1);
    VI cnt(n + 1);

    Q.emplace(x);
    inQ[x] = true;
    d[x] = 0;

    while(!Q.empty())
    {
        x = Q.front();
        inQ[x] = false;
        Q.pop();

        for (auto& y : G[x])
        {

            if (d[y.second] > y.first + d[x])
            {
                d[y.second] = y.first + d[x];
                if (!inQ[y.second])
                {
                    inQ[y.second] = true;
                    Q.emplace(y.second);
                }

                cnt[y.second]++;

                if (cnt[y.second] > n)
                {
                    cicluNegativ = true;
                    return;
                }
            }
        }

    }
}

int main()
{
    fin >> n >> m;
    G = VVPI(n + 1);
    d = VI(n + 1, INF);
    int x, y, w;

    for (int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> w;
        G[x].emplace_back(w, y);
    }

    BellmanFord(1);

    if (!cicluNegativ)
        for (int i = 2; i <= n; ++i)
            fout << d[i] << ' ';
    else
        fout << "Ciclu negativ!";

}