Pagini recente » Cod sursa (job #3285608) | Autentificare | Cod sursa (job #3294102) | Cod sursa (job #235716) | Cod sursa (job #3287885)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
const int N = 50000;
struct succesor
{
int vf, cost;
};
int n, m, d[N+1], nrq[N+1];
bool inq[N+1];
vector <succesor> s[N+1];
bool bellman_ford(int x0)
{
for (int i = 1; i <= n; i++)
{
d[i] = INT_MAX;
inq[i] = false;
nrq[i] = 0;
}
queue <int> q;
q.push(x0);
d[x0] = 0;
inq[x0] = true;
nrq[x0]++;
while (!q.empty())
{
int x = q.front();
q.pop();
inq[x] = false;
for (auto p: s[x])
{
int y = p.vf;
int c = p.cost;
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");
in >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y, c;
in >> x >> y >> c;
s[x].push_back((succesor){y, c});
}
if (!bellman_ford(1))
{
out << "Ciclu negativ!\n";
}
else
{
for (int i = 2; i <= n; i++)
{
out << d[i] << " ";
}
out << "\n";
}
in.close();
out.close();
return 0;
}