Pagini recente » Cod sursa (job #3289616) | Cod sursa (job #3293561) | Cod sursa (job #3293565) | Cod sursa (job #3292823) | Cod sursa (job #3287932)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
struct nod
{
int next, cost;
};
bool bellman_ford(int start, int n, vector<vector<nod>> &g, vector<int> &dist, vector<int> &nrq, vector<bool> &inq)
{
queue<int> q;
q.push(start);
dist[start] = 0;
inq[start] = true;
nrq[start] = 1;
while (!q.empty())
{
int x = q.front();
q.pop();
inq[x] = false;
for (auto nb : g[x])
{
int next = nb.next, cost = nb.cost;
if (dist[x] + cost < dist[next])
{
dist[next] = dist[x] + cost;
if (!inq[next])
{
q.push(next);
inq[next] = true;
nrq[next]++;
if (nrq[next] == n)
{
return false;
}
}
}
}
}
return true;
}
int main()
{
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n, m;
in >> n >> m;
vector<vector<nod>> g(n + 1);
vector<int> dist(n + 1, INT_MAX), nrq(n + 1, 0);
vector<bool> inq(n + 1, false);
for (int i = 1; i <= m; i++)
{
int x, y, c;
in >> x >> y >> c;
g[x].push_back({y, c});
}
if (!bellman_ford(1, n, g, dist, nrq, inq))
{
out << "Ciclu negativ!";
}
else
{
for (int i = 2; i <= n; i++)
{
out << dist[i] << " ";
}
}
return 0;
}