Cod sursa(job #2148432)

Utilizator tanasaradutanasaradu tanasaradu Data 1 martie 2018 18:34:42
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 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);
queue < int > Q;
int n , m , dist[Nmax] , freq[Nmax];
vector < pair < int , int > > L[Nmax];
bool viz[Nmax];
int main()
{
    int x , y , c;
    bool cycle = 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;
    freq[1] = 1;
    Q . push(1);
    while(! Q . empty() && !cycle)
    {
        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(!viz[w . first])
            {
                viz[w . first] = true;
                 ++freq[w . first];
                 if(freq[w . first] > n)
                    cycle = true;
                 Q . push(w . first);
            }
        }
    }
    if(cycle)
        fout << "Ciclu negativ!\n";
    else
    {
        for(int i = 2 ; i <= n ; i++)
                fout << dist[i] << " ";
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}