Cod sursa(job #2120298)

Utilizator tanasaradutanasaradu tanasaradu Data 2 februarie 2018 11:52:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int Nmax =  50005;
const int inf = (1 << 30);
int dist[Nmax] , n , m , nr[Nmax];
vector < pair < int , int > > L[Nmax];
bool viz[Nmax];
queue < int > Q;
int main()
{
    int x , y , c;
    bool ok = false;
    fin >> n >> m;
    for(int i = 1 ; i <= m ; i++)
    {
        fin >> x >> y >> c;
        L[x] . push_back({y , c});
    }
    for(int i = 1 ; i <= n ; i++)
        dist[i] = inf;
    dist[1] = 0;
    viz[1] = true;
    Q . push(1);
    while(! Q . empty() && !ok)
    {
        x = Q . front();
        Q . pop();
        viz[x] = false;
        for(auto w : L[x])
        {
            if(dist[w . first] > dist[x] + w . second)
            {
                dist[w . first] = dist[x] + w . second;
                if(nr[w . first] > n)
                    ok = true;
                else if(!viz[w . first])
                {
                    viz[w . first] = true;
                    nr[w . first]++;
                    Q . push(w . first);
                }
            }
        }
    }
    if(ok == true)
        fout << "Ciclu negativ!\n";
    else
    {
        for(int i = 2 ; i <= n ; i++)
            fout << dist[i] << " ";
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}