Cod sursa(job #3373602)

Utilizator mlupseLupse-Turpan Mircea mlupse Data 7 noiembrie 2026 12:50:21
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#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];
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;

    for(int k = 1; k <= N; ++k)
        for(int i = 1; i <= N; ++i)
            for(auto it : G[i])
            {
                int Vecin = it.first, Cost = it.second;
                D[Vecin] = min(D[Vecin], D[i] + Cost);
            }
    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;
}