Pagini recente » Cod sursa (job #3176362) | Cod sursa (job #1547055) | Cod sursa (job #2347656) | Cod sursa (job #2500102) | Cod sursa (job #2722890)
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
vector <pair <int, int>> v[50001];
queue <int> q;
int d[50001], opt[50001];
bool b[50001];
bool bellman (int n)
{
int i, na, x, y;
for (i = 1; i<=n; i++)
d[i] = 1<<30;
d[1] = 0;
q.push(1);
b[1] = 1;
while (q.empty() == 0)
{
na = q.front();
q.pop();
b[na] = 0;
for (i = 0; i<v[na].size(); i++)
{
x = v[na][i].first;
y = v[na][i].second;
if (d[na] + y < d[x])
{
d[x] = d[na] + y;
if (b[x] == 0)
{
q.push(x);
b[x] = 1;
opt[x]++;
if (opt[x] >= n)
return 0;
}
}
}
}
return 1;
}
int main()
{
int n, m, i, x, y, z;
bool rasp;
fin >> n >> m;
for (i = 1; i<=m; i++)
{
fin >> x >> y >> z;
v[x].push_back({y, z});
}
rasp = bellman (n);
if (rasp == 0)
fout << "Ciclu negativ!";
else
for (i = 2; i<=n; i++)
fout << d[i] << ' ';
return 0;
}