Cod sursa(job #2377132)

Utilizator My_Road_To_ONIAndrei Panainte My_Road_To_ONI Data 8 martie 2019 22:08:53
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>

using namespace std;

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

const int Nmax =  50005;
const int oo = (1 << 30);

struct Graf
{
    int nod, cost;
    inline bool operator < (const Graf &A) const
    {
        return cost > A.cost;
    }
};

priority_queue <Graf> Q;
vector < pair < int, int > > L[Nmax];

int n, m;
int dist[Nmax], freq[Nmax];
bool viz[Nmax];
bool cycle;

void Read()
{
    int i;
    int x, y, c;
    fin >> n >> m;
    for(i = 1 ; i <= m ; i++)
    {
        fin >> x >> y >> c;
        L[x] . push_back({y, c});
    }
    fin.close();
}

void Init()
{
    int i;
    for(i = 1 ; i <= n ; i++)
        dist[i] = oo;
}

void BellmanFord()
{
    Graf w, w1;
    cycle = false;
    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 k : L[w.nod])
            if(dist[k.first] > dist[w.nod] + k.second)
            {
                dist[k.first]  = dist[w.nod] + k.second;
                ++freq[k.first];
                if(freq[k.first] > n) cycle = true;
                if(!viz[k.first])
                {
                    viz[k.first] = true;
                    w1 = {k.first, dist[k.first]};
                    Q.push(w1);
                }
            }
    }
}

void Write()
{
    int i;
    if(cycle)
        fout << "Ciclu negativ!\n";
    else
    {
        for(i = 2 ; i <= n ; i++)
            fout << dist[i] << " ";
        fout << "\n";
    }
    fout.close();
}

int main()
{
    Read();
    Init();
    BellmanFord();
    Write();
    return 0;
}