Cod sursa(job #3377077)

Utilizator R_2008Nechitescu Radu-Andrei R_2008 Data 21 noiembrie 2026 14:03:21
Problema Flux maxim de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 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;
int N,M; int D[NMax + 5]; int NrQ[NMax + 5];
bool InQ[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;
    Q.push(1);
    int Ok = 1;
    while(!Q.empty() && Ok)
        {
            int i = Q.front(); Q.pop();InQ[i] = false;
            for(auto it : G[i])
            {
                int Vecin = it.first, Cost = it.second;
                if(D[Vecin] > D[i] + Cost)
                    {
                        D[Vecin] = D[i] + Cost;
                        if(!InQ[Vecin])
                        {
                            Q.push(Vecin);
                            InQ[Vecin] = true;
                        }
                        NrQ[Vecin]++;
                        if(NrQ[Vecin] >= N)
                            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;
}