Cod sursa(job #3286973)

Utilizator Torna3oVirtopeanu Andrei Torna3o Data 14 martie 2025 21:11:01
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

const int NMAX = 50000 + 1;
const long long INF = (1LL << 60);
vector< pair <int, int> > G[NMAX];
queue<int> q;
long long cost[NMAX];
int vis[NMAX], n;
bool ok = true;


void BellmanFord(int source)
{
    cost[source] = 0;
    q.push(source);

    while(!q.empty())
    {
        int node = q.front();
        q.pop();
        for(auto neigh : G[node])
        {
            int nn = neigh.first;
            int nd = neigh.second;
            if(cost[node] + nd < cost[nn])
            {
                cost[nn] = cost[node] + nd;
                vis[nn]++;
                if(vis[nn] > n)
                {
                    out << "Ciclu negativ!";
                    ok = false;
                    return;
                }
                q.push(nn);
            }
        }
    }
}

int main()
{
    int m, x, y, c;
    in >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        in >> x >> y >> c;
        G[x].push_back({y, c});
    }

    for(int i = 1; i <= n; i++)
    {
        cost[i] = INF;
    }

    BellmanFord(1);

    if(ok)
    {
        for(int i = 2; i <= n; i++)
        {
            out << cost[i] << " ";
        }
    }

    return 0;
}