Pagini recente » Cod sursa (job #1126188) | Cod sursa (job #2816323) | Cod sursa (job #131662) | Cod sursa (job #2770327) | Cod sursa (job #2881970)
#include <bits/stdc++.h>
#define DIM 50005
#define INF 0x3f3f3f3f
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m, nriq[DIM], d[DIM];
bitset <DIM> iq;
queue <int> q;
vector <pair <int, int>> edges[DIM];
bool bf()
{
iq[1] = 1;
nriq[1] = 1;
q.push(1);
for (int i = 1; i <= n; i++)
d[i] = INF;
d[1] = 0;
while (!q.empty())
{
int node = q.front();
q.pop();
iq[node] = 0;
for (auto child: edges[node])
{
int childNode = child.first;
int cost = child.second;
if (d[childNode] > d[node] + cost)
{
d[childNode] = d[node] + cost;
if (!iq[childNode])
{
q.push(childNode);
iq[childNode] = 1;
nriq[childNode]++;
if (nriq[childNode] == n)
return 0;
}
}
}
}
return 1;
}
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, cost;
f >> x >> y >> cost;
edges[x].push_back(make_pair(y, cost));
}
if (!bf())
{
g << "Ciclu negativ!";
return 0;
}
for (int i = 2; i <= n; i++)
g << d[i] << " ";
return 0;
}