Cod sursa(job #2718317)

Utilizator Costea_AlexandruCostea Alexandru Costea_Alexandru Data 8 martie 2021 17:39:47
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fi("bellmanford.in");
ofstream fo("bellmanford.out");
int n,m,i,j,c,k,d[50001], nrap[50001];
const int inf = 1<<29;
vector<pair<int,int>>v[50001];
queue<int>q;
bool vz[50001], negativ;

void BellmanFord( bool &negativ)
{
    int i,x,nod,cost;
    size_t j;
    negativ = false;
    for(i=1; i<=n; i++)
        d[i] = inf;
    d[1] = 0;
    q.push(1);
    vz[1] = true;
    while(!q.empty() && !negativ)
    {
        x = q.front();
        q.pop();
        vz[x] = false;
        for(j=0; j<v[x].size(); j++)
        {
            nod = v[x][j].first;
            cost = v[x][j].second;
            if(d[nod] > d[x] + cost)
            {
                d[nod] = d[x] + cost;
                if(!vz[nod])
                {
                    if(nrap[nod] > n)
                        negativ = true;
                    else
                    {
                        q.push(nod);
                        vz[nod] = true;
                        nrap[nod]++;
                    }
                }
            }
        }
    }
}
int main()
{
    fi >> n >> m;
    for(k=1; k<=m; k++)
    {
        fi >> i >> j >> c;
        v[i].push_back(make_pair(j,c));
    }
    BellmanFord(negativ);
    if(negativ)
    {
        fo << "Ciclu negativ!";
    }
    else
    {
        for(i=2; i<=n; i++)
            fo << d[i] << " ";
    }
}