Cod sursa(job #2563216)

Utilizator mihai03Mihai Grigore mihai03 Data 1 martie 2020 08:40:50
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int nmax = 50005;
const int inf = (1 << 30);
int n, m;
vector < pair < int , int > > G[nmax];

int d[nmax];
int viz[nmax];
bool inQueue[nmax];
queue < int > q;

bool BellmanFord(int startNode)
{
    for(int i = 1; i <= n; i++)
    {
        d[i] = inf;
    }
    d[startNode] = 0;
    inQueue[startNode] = true;
    q.push(startNode);
    while(!q.empty())
    {
        int nodCurent = q.front();
        viz[nodCurent]++;
        if(viz[nodCurent] >= n)
            return false;
        inQueue[nodCurent] = false;
        q.pop();
        for(int i = 0; i < G[nodCurent].size(); i++)
        {
            int vecin = G[nodCurent][i].first;
            int cost = G[nodCurent][i].second;
            if(d[nodCurent] + cost < d[vecin])
            {
                d[vecin] = d[nodCurent] + cost;
                if(inQueue[vecin] == false)
                {
                    inQueue[vecin] = true;
                    q.push(vecin);
                }
            }
        }
    }
    return true;
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y,c));
    }
    if(BellmanFord(1) == false)
    {
        fout << "Ciclu negativ!";
    }
    else
    {
        for(int i = 2; i <= n; i++)
        {
                fout << d[i] << " ";
        }
    }

    return 0;
}