Cod sursa(job #2478547)

Utilizator stefantagaTaga Stefan stefantaga Data 22 octombrie 2019 13:07:36
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
#define INF 100000000
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,i,x,y,cost;
vector <pair <int,int > > v[50005];
queue <int > q;
int d[50005],lg[50005],nod,use[50005];
int main()
{
    f>>n>>m;
    for (i=1;i<=m;i++)
    {
        f>>x>>y>>cost;
        v[x].push_back({y,cost});
    }
    q.push(1);
    for (i=1;i<=n;i++)
    {
        d[i]=INF;
    }
    d[1]=0;
    lg[1]=1;
    while (!q.empty())
    {
        nod=q.front();
        use[nod]=0;
        q.pop();
        for (i=0;i<v[nod].size();i++)
        {
            if (d[nod]+v[nod][i].second<d[v[nod][i].first])
            {
                d[v[nod][i].first]=d[nod]+v[nod][i].second;
                if (use[v[nod][i].first]==0)
                {
                    q.push(v[nod][i].first);
                    use[v[nod][i].first]=1;
                }
                lg[v[nod][i].first]=lg[nod]+1;
                if (lg[v[nod][i].first]>n)
                {
                    g<<"Ciclu negativ!";
                    return 0;
                }
            }
        }
    }
    for (i=2;i<=n;i++)
    {
        g<<d[i]<<" ";
    }
    return 0;
}