Pagini recente » Cod sursa (job #1166973) | Cod sursa (job #1348789) | Cod sursa (job #899387) | Cod sursa (job #209857) | Cod sursa (job #2670305)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair <int, int>> v[50001];
queue <int> q;
bool b[50001];
int d[50001], cnt[50001];
bool bf(int n)
{
int na, i, x, y;
for (i = 1; i<=n; i++)
d[i] = 1<<30;
d[1] = 0;
b[1] = 1;
q.push(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[x] > d[na] + y)
{
d[x] = d[na] + y;
if (b[x] == 0)
{
b[x] = 1;
cnt[x]++;
if (cnt[x] == n)
return 0;
q.push(x);
}
}
}
}
return 1;
}
int main()
{
int i, n, m, x, y, z;
fin >> n >> m;
for (i = 1; i<=m; i++)
{
fin >> x >> y >> z;
v[x].push_back({y, z});
}
if (bf(n) == 0)
fout << "Ciclu negativ!";
else
for (i = 2; i<=n; i++)
fout << d[i] << ' ';
return 0;
}