Cod sursa(job #3270173)

Utilizator StefantimStefan Timisescu Stefantim Data 22 ianuarie 2025 12:39:33
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>

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

const int NMAX = 50005;
const int inf = 0x3f3f3f3f;


vector <vector <pair <int, int>>> v(NMAX); // pair{catre_varful, cost}
vector <int> f(NMAX), d(NMAX, inf), cnt(NMAX); //initializam distantele cu infinit
queue <int> q;

void bellman(int n)
{
    q.push(1);
    f[1] = 1;
    d[1] = 0;

    while(!q.empty())
    {
        int a = q.front();
        q.pop();
        f[a] = 0;

        for(auto e: v[a])
        {
            if(d[a] + e.second < d[e.first])
            {
                d[e.first] = d[a] + e.second;
                
                if(!f[e.first])
                {
                    cnt[e.first]++;
                    if(cnt[e.first] >= n)
                    {
                        fout << "Ciclu negativ!";
                        exit(0);
                    }
                    q.push(e.first);
                    f[e.first] = 1;
                }
            }
        }
    }
}

int main()
{
    int n, m, x, y, c;

    fin >> n >> m;
    for(int i = 0; i < m; ++i)
    {
        fin >> x >> y >> c;
        v[x].push_back({y,c});
    }

    bellman(n);

    for(int i = 2; i <= n; ++i)
        fout << d[i] << " ";
    
    return 0;
}