Pagini recente » Cod sursa (job #2132447) | Cod sursa (job #2809960) | Cod sursa (job #2522561) | Cod sursa (job #993118) | Cod sursa (job #2764908)
#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 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[startNode] = 0;
Q.push(startNode);
inQueue[startNode] = true;
while (Q.empty() == false)
{
int node = Q.front();
Q.pop();
inQueue[node] = false;
cntVisited[node]++;
if (cntVisited[node] >= n)
{
return false;
}
for (int i = 0; i < V[node].size(); i++)
{
int neighbour = V[node][i].first;
int cost = V[node][i].second;
if (dist[node] + cost < dist[neighbour])
{
dist[neighbour] = dist[node] + cost;
if (inQueue[neighbour] == false)
{
Q.push(neighbour);
inQueue[neighbour] = true;
}
}
}
}
return true;
}
int main()
{
Read();
if (BellmanFord(1) == false)
{
g << "Ciclu negativ!";
}
else
{
for (int i = 2; i <= n; i++)
{
g << dist[i] << " ";
}
}
}