Cod sursa(job #2840235)

Utilizator paulm238Madaras Paul paulm238 Data 27 ianuarie 2022 11:27:38
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 50005;
const int inf = 2e9;

int n, m, x, y, z, d[nmax], viz[nmax], e;

vector <pair <int, int> > g[nmax];
queue <int> q;
bool inQueue[nmax];

bool bellmanford(int s)
{
    for(int i = 1; i <= n; i++ )
        d[i] = inf;
    d[s] = 0;
    q.push(s);
    inQueue[s] = true;
    while(!q.empty())
    {
        e = q.front();
        q.pop();
        viz[e] ++;
        inQueue[e] = false;

        if(viz[e] >= n)
            return false;

        for(auto next: g[e])
        {
            if(d[next.first] > d[e] + next.second)
            {
                d[next.first] = d[e] + next.second;
                if(inQueue[next.first] == false)
                {
                    q.push(next.first);
                    inQueue[next.first] = true;
                }
            }
        }
    }
    return true;
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; i ++)
    {
        in >> x >> y >> z;
        g[x].push_back({y,z});
    }
    in.close();
    if(bellmanford(1))
    {
        for(int i = 2; i <= n; i ++)
            out << d[i] << " ";
    }
    else
        out << "Ciclu negativ!";
    out.close();
    return 0;
}