Cod sursa(job #3373622)

Utilizator mlupseLupse-Turpan Mircea mlupse Data 7 noiembrie 2026 13:18:43
Problema Algoritmul Bellman-Ford Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int NMax = 50000;
const int oo = 1e9;
vector < pair <int, int> > G[NMax + 5];
queue <int> Q[2];
int N,M; int D[NMax + 5];
void Read()
{
    fin >> N >> M;
    for(int i = 1; i <= M; ++i)
    {
        int x,y,c;
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y,c));
    }
}

void BellmanFord()
{
    for(int i = 2; i <= N; ++i)
        D[i] = oo;
    int current = 0, next = 1;
    Q[current].push(1);
    for(int k = 1; k <= N; ++k)
    {
        while(!Q[current].empty())
        {
            int i = Q[current].front(); Q[current].pop();
            for(auto it : G[i])
            {
                int Vecin = it.first, Cost = it.second;
                if(D[Vecin] > D[i] + Cost)
                    {
                        D[Vecin] = D[i] + Cost;
                        Q[next].push(Vecin);
                    }
            }
        }
        swap(current, next);
    }
    int Ok = 1;
    for(int i = 1; i <= N; ++i)
        for(auto it : G[i])
            {
                int Vecin = it.first, Cost = it.second;
                if(D[Vecin] > D[i] + Cost)
                    Ok = 0;
            }
    if(Ok == 0)
    {
        fout << "Ciclu negativ!";
        return;
    }
    for(int i = 2; i <= N; ++i)
        fout << D[i] << " ";
}

int main()
{
    Read();
    BellmanFord();
    return 0;
}