Pagini recente » Cod sursa (job #1875392) | Cod sursa (job #1158117) | Cod sursa (job #3218828) | Cod sursa (job #2041103) | Cod sursa (job #2764941)
#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;
void Read()
{
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()
{
Read();
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