Cod sursa(job #2837458)

Utilizator robertanechita1Roberta Nechita robertanechita1 Data 22 ianuarie 2022 10:50:39
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
#define oo 2000000009

using namespace std;

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

vector<pair<int, int> > L[50002];
        ///nod, cost
int n, viz[50004], d[50002]; ///d[i] = costul minim pana la nodul i
int contor[50002]; //de cate ori am pus nodul i in coada
queue <int> q;

void Citire()
{
    int x, y, c, m;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        L[x].push_back({y, c});
    }
}

void BellmanFord()
{
    int i, x, c;
    bool existNegative;
    for(int i = 2; i <= n; i++)
        d[i] = oo;
    existNegative = false;
    viz[1] = 1;
    q.push(1);
    contor[1] = 1;
    while(!q.empty() && !existNegative)
    {
        x = q.front();
        q.pop();
        viz[x] = 0;
        for(auto w : L[x])
        {
            i = w.first;
            c = w.second;
            if(d[i] > d[x] + c)
            {
                d[i] = d[x] + c;
                if(viz[i] == 0)
                {
                    if(contor[i] > n)
                        existNegative = true;
                    else
                    {
                        q.push(i);
                        viz[i] = 1;
                        contor[i]++;
                    }
                }
            }
        }
    }
    if(existNegative)
        fout << "Ciclu negativ!";
    else
    {
        for(int i = 2; i <= n; i++)
            fout << d[i] << " ";
        fout << "\n";
    }
}

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