Cod sursa(job #2837670)

Utilizator Alle43221Moroz Alexandra-Ioana Alle43221 Data 22 ianuarie 2022 13:16:03
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

#define inf 2000000001
#define nmax 50001

using namespace std;

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

struct Muchie
{
    int y, cost;
} aux;

int n, m, x, mnv;
bool ok=true;

bitset <nmax> vf;

vector <int> D;
queue <int> q;

int main()
{
    fin>>n>>m;

    vector <Muchie> C[n+1];

    for(int i=0; i<m; i++)
    {
        fin>>x>>aux.y>>aux.cost;
        C[x].push_back(aux);
    }

    vector <int> cate(n+1, 0);
    D.assign(n+1, inf);

    D[1]=0;
    q.push(1);
    vf[1]=1;
    while(!q.empty())
    {
        mnv=q.front();
        q.pop();
        vf[mnv]=0;
        for(auto i: C[mnv])
        {
            if(D[mnv]+i.cost<D[i.y])
            {
                D[i.y]=D[mnv]+i.cost;
                if(!vf[mnv])
                {
                    q.push(i.y);
                    vf[i.y]=1;
                    cate[i.y]++;
                }

                if(cate[i.y]>=n)
                {
                    ok=false;
                }
            }
        }
    }

    if(!ok)
    {
        fout<<"Ciclu negativ!";
    }
    else
    {
        for(int i=2; i<=n; i++)
        {
            fout<<D[i]<<' ';
        }
    }

    fin.close();
    fout.close();
    return 0;
}