Cod sursa(job #2529000)

Utilizator AlexandruGabrielAliciuc Alexandru AlexandruGabriel Data 22 ianuarie 2020 20:44:14
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
#define N 50005
#define INF INT_MAX

using namespace std;

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

int n, m, cost[N], cntViz[N];
bool inCoada[N], ciclu;
queue <int> Q;
vector < pair <int, int> > L[N];

void Citire()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        fin >> a >> b >> c;

        L[a].push_back(make_pair(b, c));
    }
}

void Solve()
{
    for (int i = 2; i <= n; i++)
        cost[i] = INF;

    cntViz[1] = 1;
    Q.push(1);
    inCoada[1] = 1;

    while (!Q.empty() && !ciclu)
    {
        int nod = Q.front();
        Q.pop();
        inCoada[nod] = 0;

        for (auto i : L[nod])
        {
            int nextNod = i.first;
            int costMuchie = i.second;

            if (cost[nextNod] > cost[nod] + costMuchie)
            {
                cost[nextNod] = cost[nod] + costMuchie;
                cntViz[nextNod]++;

                if (cntViz[nextNod] == n)
                    ciclu = 1;
                else
                {
                    if (!inCoada[nextNod])
                    {
                        Q.push(nextNod);
                        inCoada[nextNod] = 1;
                    }

                }
            }
        }
    }

    if (ciclu)
        fout << "Ciclu negativ!";
    else
        for (int i = 2; i <= n; i++)
            fout << cost[i] << " ";

}

int main()
{
    Citire();
    Solve();
    return 0;
}