Cod sursa(job #2837673)

Utilizator Alle43221Moroz Alexandra-Ioana Alle43221 Data 22 ianuarie 2022 13:20:03
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 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, mnv;

bitset <nmax> vf;

vector <int> D;
queue <int> q;
vector <Muchie> C[nmax];


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

    D[x]=0;
    q.push(x);
    vf[x]=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)
                {
                    return 0;
                }
            }
        }
    }
    return 1;
}

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

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

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

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