Cod sursa(job #3004014)

Utilizator CobzaruAntonioCobzaru Paul-Antonio CobzaruAntonio Data 16 martie 2023 08:39:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin ("bellmanford.in");
ofstream cout ("bellmanford.out");
int d[50005];
int f[50005];
int n,m;
vector < pair<int,int> > g[50005];
struct element
{
    int vf,c;
};
class Comparare
{
public:
    bool operator() (element a,element b)
    {
        if (a.c > b.c)
            return true;
        return false;
    }
};
priority_queue <element,vector<element>,Comparare> q;
bool bellman (int inceput)
{
    for (int i=1;i<=n;i++)
        d[i] = 2e9;
    d[inceput] = 0;
    element aux;
    aux.vf = inceput;
    aux.c = 0;
    f[inceput] = 1;
    q.push(aux);
    while (!q.empty())
    {
        aux = q.top();
        q.pop();
        int nod = aux.vf;
        if (d[nod]!=aux.c)
            continue;
        for (auto muchie:g[nod])
        {
            if (d[muchie.first] > d[nod] + muchie.second)
            {
                d[muchie.first] = d[nod] + muchie.second;
                aux.vf = muchie.first;
                aux.c = d[muchie.first];
                q.push(aux);
                f[muchie.first]++;
                if (f[muchie.first] > n)
                    return false;
            }
        }
    }
    return true;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for (int i=1;i<=m;i++)
    {
        int x,y,c;
        cin >> x >> y >> c;
        g[x].push_back({y,c});
    }
    bool rasp = bellman(1);
    if (rasp == false)
    {
        cout << "Ciclu negativ!";
        return 0;
    }
    for (int i=2;i<=n;i++)
        cout << d[i] << ' ';
    return 0;
}