Cod sursa(job #2720600)

Utilizator andrei_laurentiuRadu Andrei-Laurentiu andrei_laurentiu Data 11 martie 2021 00:56:03
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

using namespace std;

const int nmax = 50005, val_mare = 1500005;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

int n, m, dist[nmax], contor_in_coada[nmax], negative_cycle;
struct cmp
{
    bool operator() (int x, int y)
    {
        return dist[x] > dist[y];
    }
};
vector< pair<int, int> > list_vec[nmax];
priority_queue < int, vector<int>, cmp> pq;


void bellman_ford(int start)
{
    int i, curent, cost, vecin;
    bitset <nmax> in_coada(false);
    for(i = 1; i <= n; ++i)
        dist[i] = val_mare;
    in_coada.set(start);
    pq.push(start);
    negative_cycle = 0;
    dist[start] = 0;

    while(!pq.empty() && !negative_cycle)
    {
        curent = pq.top();
        pq.pop();
        in_coada.reset(curent);
        for(auto a : list_vec[curent])
        {
            vecin = a.first;
            cost = a.second;
            if(dist[curent] + cost < dist[vecin])
            {
                dist[vecin] = dist[curent] + cost;
                if(!in_coada[vecin])
                {
                    if(contor_in_coada[vecin] > n)
                        negative_cycle = 1;
                    else
                    {
                        in_coada.set(vecin);
                        pq.push(vecin);
                        contor_in_coada[vecin]++;
                    }
                }
            }
        }
    }
}
int main()
{
    int i, u, v, c;
    fin>>n>>m;
    for(i = 1; i <= n; ++i)
    {
        fin>>u>>v>>c;
        list_vec[u].push_back({v, c});
    }

    bellman_ford(1);

    if(negative_cycle)
        fout<<"Ciclu negativ!";
    else
    {
        for(i = 2; i <= n; ++i)
            fout<<dist[i]<<' ';
    }
    return 0;
}