Cod sursa(job #2502117)

Utilizator grecubogdanGrecu Bogdan grecubogdan Data 30 noiembrie 2019 13:06:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
queue <int> q;
vector <pair<int,int>> G[50005];
int n,m,x,y,c,i,d[50005],nr[50005];
int sel[50005];
int Bellmanford()
{
    int i,ok=0;
     for(i=1; i<=n; i++)
    {   d[i]=50000000;
        sel[i]=0;
    }
    sel[1]=1;
    nr[1]=1;
    q.push(1);
    d[1]=0;
    while(!q.empty() && !ok)
    {   x=q.front();
        q.pop();
        sel[x]=0;
        for(auto it : G[x])
        {   if(nr[it.second]>n)
                ok=1;
            if(d[x]+it.first<d[it.second])
            {   d[it.second]=d[x]+it.first;
                if(!sel[it.second])
                {   q.push(it.second);
                    sel[it.second]=1;
                }
                nr[it.second]=nr[x]+1;
                if(nr[it.second]>n)
                    ok=1;
            }
        }
    }
    return ok;
}
int main()
{   f>>n>>m;
    for(i=1; i<=m; ++i)
    {   f>>x>>y>>c;
        G[x].push_back({c,y});
    }
    if(Bellmanford())
        g<<"Ciclu negativ!"<<'\n';
    else
        for(i=2; i<=n; i++)
            g<<d[i]<<' ';
    return 0;
}