Cod sursa(job #2378840)

Utilizator ilie0712Botosan Ilie ilie0712 Data 12 martie 2019 17:52:38
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

const int INF=5000001;
const int N=50001;
int n,m,d[N],nrq[N];
bool inq[N];

queue <int> q;
vector <pair<int,int>> a[N];

void citire()
{
    int x,y,c;
    in>>n>>m;
    for(int i=1; i<=m; ++i)
    {
        in>>x>>y>>c;
        a[x].push_back(make_pair(y,c));
    }
}
void bellman_ford(int x)
{

    for(int i=1; i<=n; ++i) d[i]=INF;
    q.push(x);

    d[x]=0;
    inq[x]=true;
    nrq[x]++;

    while(!q.empty())
    {
        x=q.front();
        q.pop();
        inq[x]=false;
        int y,c;
        for(auto p: a[x])
        {
            y=p.first;
            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)
                    {
                        out<<"Ciclu negativ";
                        return ;
                    }
                }
            }
        }
    }
}

int main()
{
    citire();
    bellman_ford(1);
    for(int i=2; i<=n; ++i) out<<d[i]<<" ";
    return 0;
}