Pagini recente » Cod sursa (job #3177328) | Cod sursa (job #603347) | Cod sursa (job #2004070) | Cod sursa (job #2854677) | Cod sursa (job #2734880)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int N = 50001;
const int INF = 1e9;
vector < pair<int, int>> a[N];
int d[N], nrq[N], n;
bool inq[N];
queue <int> q;
bool bf(int x0)
{
for (int i = 1; i <= n; i++)
{
if (i != x0)
{
d[i] = INF;
}
else
{
d[i] = 0;
}
}
q.push(x0);
inq[x0] = true;
nrq[x0]++;
while (!q.empty())
{
int x = q.front();
q.pop();
inq[x] = false;
for (auto p: a[x])
{
int y = p.first;
int c = p.second;
if (d[x] + c < d[y])
{
d[y] = d[x] + c;
if (!inq[y])
{
q.push(y);
inq[y] = true;
nrq[y]++;
if (nrq[y] == n)
{
return false;
}
}
}
}
}
return true;
}
int main()
{
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int m;
in >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y, c;
in >> x >> y >> c;
a[x].push_back({y, c});
}
in.close();
if (bf(1))
{
for (int i = 2; i <= n; i++)
{
out << d[i] << " ";
}
}
else
{
out << "Ciclu negativ!";
}
out.close();
return 0;
}