Cod sursa(job #2976349)

Utilizator Samoila_AlexandruSamoilaAlexandru Samoila_Alexandru Data 8 februarie 2023 23:20:21
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

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

const int nMax=5e4+5;

int n, m, x, y, cost, d[nMax];
vector<pair<int, int>> g[nMax];

bool bellman(int start)
{
    queue<int> q;
    int fr[nMax]={0};

    for(int i=1; i<=n; i++)
        d[i]=INT_MAX;

    d[start]=0;
    q.push(start);
    while(!q.empty())
    {
        int nod=q.front();
        q.pop();
        fr[nod]++;

        if(fr[nod]>n)
            return false;

        for(auto& i: g[nod])
        {
            int nodNou=i.first;
            int costNou=i.second;

            if(d[nodNou] > d[nod]+costNou)
            {
                d[nodNou]=d[nod]+costNou;
                q.push(nodNou);
            }
        }
    }

    return true;
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(0);

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

    if(!bellman(1))
        fout<<"Ciclu negativ!";
    else for(int i=2; i<=n; i++)
        fout<<d[i]<<' ';

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