Cod sursa(job #2152809)

Utilizator tanasaradutanasaradu tanasaradu Data 5 martie 2018 20:12:24
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 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);
struct Graf
{
    int nod , cost;
    bool operator < (const Graf & e ) const
    {
        return cost > e . cost;
    }
};
priority_queue <Graf> Q;
int n, m, dist[Nmax], freq[Nmax];
vector < pair < int, int > > L[Nmax];
bool viz[Nmax];
int main()
{
    int x, y, c;
    Graf w , w1;
    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;
    w = {1 , 0};
    Q . push(w);
    while(! Q . empty() && !cycle)
    {
        w = Q . top();
        Q . pop();
        viz[w . nod] = false;
        for(auto pas : L[w . nod])
            if(dist[pas . first] > dist[w . nod] + pas . second)
            {
                dist[pas . first]  = dist[w . nod] + pas . second;
                ++freq[pas . first];
                if(freq[pas . first] > n)
                    cycle = true;
                if(!viz[pas . first])
                {
                    viz[pas . first] = true;
                    w1 = {pas . first , dist[pas . first]};
                    Q . push(w1);
                }
            }
    }
    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;
}