# Cod sursa(job #2764941)

Utilizator Data 23 iulie 2021 19:07:00 Algoritmul Bellman-Ford 10 cpp-64 done Arhiva educationala 1.9 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int POSITIVE_INFINITY = (1 << 31) - 1;
const int NEGATIVE_INFINITY = -(1 << 31);
const int MAX = 50001;

int n, m, cntVisited[MAX], dist[MAX];
bool inQueue[MAX];
vector <pair <int, int>> V[MAX];
queue <int> Q;

{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, z;
f >> x >> y >> z;
V[x].push_back(make_pair(y, z));
}
}

bool BellmanFord(int startNode)
{
for (int i = 1; i <= n; i++)
{
dist[i] = POSITIVE_INFINITY;
}
dist[1] = 0;

for (int k = 1; k < m; k++)
{
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < V[i].size(); j++)
{
int neighbour = V[i][j].first;
int cost = V[i][j].second;
if (dist[i] + cost < dist[neighbour])
{
dist[neighbour] = dist[i] + cost;
}
}
}
}

for (int i = 1; i <= n; i++)
{
for (int j = 0; j < V[i].size(); j++)
{
int neighbour = V[i][j].first;
int cost = V[i][j].second;
if (dist[i] + cost < dist[neighbour] || dist[i] == NEGATIVE_INFINITY)
{
dist[neighbour] = NEGATIVE_INFINITY;
return false;
}
}
}

return true;
}

int main()
{
if (BellmanFord(1) == false)
{
g << "Ciclu negativ!";
}
else
{
for (int i = 2; i <= n; i++)
{
g << dist[i] << " ";
}
}
}

//10 13
//
//1 2 5
//2 7 60
//2 6 30
//2 4 20
//4 3 10
//4 5 75
//3 4 -15
//5 10 100
//6 9 50
//6 7 5
//6 5 25
//7 8 -50
//8 9 -10