Pagini recente » Cod sursa (job #901147) | Cod sursa (job #796551) | Cod sursa (job #1885593) | Cod sursa (job #1013807) | Cod sursa (job #2615250)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define INF 2500000
#define N_MAX 50001
#define M_MAX 250001
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
struct edge
{
int src, dst, cost;
} edges[M_MAX];
vector<int> timesInQueue(N_MAX, 0), distances(N_MAX, INF);
vector<bool> inQueue(N_MAX);
vector<edge> graph[N_MAX];
queue<int> q;
bool negativeCycle = false;
int n, m;
void input()
{
int a, b, c;
in >> n >> m;
for (int i = 0; i < m; i++)
{
in >> a >> b >> c;
graph[a - 1].push_back({a - 1, b - 1, c});
}
}
void output()
{
if (negativeCycle)
{
out << "Ciclu negativ!";
return;
}
for (int i = 1; i < n; i++)
{
out << distances[i] << ' ';
}
}
void bellmanFord()
{
q.push(0);
inQueue[0] = true;
timesInQueue[0]++;
distances[0] = 0;
while (q.size() > 0)
{
int cur = q.front();
q.pop();
inQueue[cur] = false;
for (auto e : graph[cur])
{
if (distances[e.dst] > distances[e.src] + e.cost)
{
distances[e.dst] = distances[e.src] + e.cost;
if (!inQueue[e.dst])
{
if (timesInQueue[e.dst] > n)
{
negativeCycle = true;
return;
}
else
{
q.push(e.dst);
inQueue[e.dst] = true;
timesInQueue[e.dst]++;
}
}
}
}
}
}
int main()
{
input();
bellmanFord();
output();
return 0;
}