Cod sursa(job #2709941)

Utilizator codruta.miron08Miron Ioana Codruta codruta.miron08 Data 21 februarie 2021 15:06:08
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define INF 0x3f3f3f3f
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair <int , int > > graph[50005];
int n,m,x,y,c;
int viz[50005],d[50005];
bool inq[50005];
queue < int > q;
bool bellmanford(int st)
{
    for(int i = 1; i <=n ;i++)
        d[i] = INF;
    d[st] = 0;
    q.push(st);
    inq[st] = 1;

    while(!q.empty())
    {
        int vf = q.front();
        q.pop();
        viz[vf]++;
        if(viz[vf] >= n)
            return false;
        viz[vf] = 0;
        for(auto &v : graph[vf])
        {
            int nod = v.first;
            int cost = v.second;
            if(d[vf] + cost < d[nod])
            {
                d[nod] = d[vf] + cost;
                if(!inq[nod])
                    q.push(nod);
            }
        }
    }
    return true;
}
int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        graph[x].push_back({y,c});
    }
    if(bellmanford(1))
        for(int i = 2; i <= n; i++)
        fout << d[i] << " ";
    else
        fout << "Ciclu negativ!";
    return 0;
}