Cod sursa(job #2434985)

Utilizator AlexNeaguAlexandru AlexNeagu Data 2 iulie 2019 18:01:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <queue>
#define nmax 50005
#define mmax 250005
#define oo 2000000005
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
vector < pair < int , int > > E[nmax + 5];
vector < int > D(nmax + 5, oo), F(nmax + 5, 0);
queue < int > Q;
int n, m, x, y, cost; bool negativ = false;
void Bell()
{
    while (!Q.empty())
    {
        int node = Q.front();
        Q.pop();
        for (auto it : E[node])
        {
            if (D[it.first] > D[node] + it.second)
            {
                D[it.first] = D[node] + it.second;
                F[it.first]++;
                Q.push(it.first);
                if (F[it.first] == n)
                {
                  negativ = true;
                  return;
                }
            }
        }
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        cin >> x >> y >> cost;
        E[x].push_back({y, cost});
    }
    D[1] = 0;
    Q.push(1);
    Bell();
    if (negativ) return cout << "Ciclu negativ!\n", 0;
    for (int i = 2; i <= n; i++) cout << D[i] << " ";
    return 0;
}