Cod sursa(job #2734878)

Utilizator DariusGhercaDarius Gherca DariusGherca Data 1 aprilie 2021 16:16:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
const int N=5e4+10;
const int INF=INT_MAX;
vector <pair<int,int>> a[N];
int n,m,d[N],nrq[N];
bool inq[N];
queue <int> q;
bool bf(int x0)
{
    for(int i=1;i<=n;i++)
    {
        if(i!=x0)
        {
            d[i]=INF;
        }
        else
        {
            d[i]=0;
        }
    }
    q.push(x0);
    inq[x0]=true;
    nrq[x0]++;
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        inq[x]=false;
        for(auto p:a[x])
        {
            int y=p.first;
            int c=p.second;
            if(d[x]+c<d[y])
            {
                d[y]=d[x]+c;
                if(!inq[y])
                {
                    q.push(y);
                    inq[y]=true;
                    nrq[y]++;
                    if(nrq[y]==n)
                    {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}
int main()
{
    f>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        f>>x>>y>>z;
        a[x].push_back({y,z});
    }
    f.close();
    if(bf(1))
    {
        for(int i=2;i<=n;i++)
        {
            g<<d[i]<<" ";
        }
    }
    else
    {
        g<<"Ciclu negativ!";
    }
    g.close();
    return 0;
}