Pagini recente » Cod sursa (job #3326503) | Cod sursa (job #3329692) | Cod sursa (job #2220296) | Cod sursa (job #896206) | Cod sursa (job #3335332)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
struct edge
{
int j,w;
};
vector <edge> vecini[50001];
bitset <50001> inQueue;
int n, m, dist[50001], cntRelxari[50001];
void BellmanFord (int start)
{
for (int i=1;i<=n;i++)
dist[i] = INT_MAX;
queue <int> q;
dist[start] = 0;
q.push(start);
inQueue[start] = 1;
cntRelxari[start] = 1;
while (!q.empty())
{
int i = q.front();
q.pop();
inQueue[i] = 0;
for (auto e : vecini[i])
{
int j = e.j;
int w = e.w;
if (dist[i] + w < dist[j])
{
dist[j] = dist[i] + w;
if (!inQueue[j])
{
q.push(j);
inQueue[j] = 1;
cntRelxari[j]++;
if (cntRelxari[j] > n - 1)
{
g<<"Ciclu negativ!";
return;
}
}
}
}
}
for (int i=1; i<=n; i++)
if (i != start)
g<<dist[i]<<" ";
}
int main()
{
f>>n>>m;
for (int i=0; i<m; i++)
{
int x, y, w;
f>>x>>y>>w;
vecini[x].push_back({y, w});
}
BellmanFord(1);
}