Cod sursa(job #2170607)

Utilizator vladbatalanBatalan Vlad vladbatalan Data 15 martie 2018 08:55:33
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>
#define mp make_pair
#define NMAX 50010
using namespace std;

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

const int oo = 100000000;
int n, m, d[NMAX], nr_count[NMAX], top, nod, cost;
bool in_stk[NMAX];
vector<pair<int, int> > v[NMAX]; /// cost, pana la nod
queue<int> coada;

int main()
{
    int x, y, z;
    for(int i=1; i<=m; i++)
    {
        fin >> x >> y >> z;
        v[x].push_back(mp(z,y));
    }
    for(int i=1; i<=n; i++)
        d[i] = oo;
    d[1] = 0;
    coada.push(1);
    in_stk[1] = 1;
    int negative = 0;
    while(!coada.empty() && !negative)
    {
        top = coada.front();
        coada.pop();
        in_stk[top] = 0;
        for(auto vec:v[top])
        {
            nod = vec.second;
            cost = vec.first;
            if(d[nod] > d[top] + cost)
            {
                d[nod] = d[top] + cost;
                if(!in_stk[nod])
                {
                    if(nr_count[nod] > n)
                    {
                        negative = 1;
                        fout<<"Ciclu negativ!\n";
                        return 0;
                    }
                    else
                    {
                        in_stk[nod] = 1;
                        nr_count[nod] ++;
                        coada.push(nod);
                    }
                }
            }
        }
    }
    for(int i=2; i<=n; i++)
        fout<<d[i]<<' ';
    return 0;
}