Pagini recente » Cod sursa (job #87398) | Cod sursa (job #1812647) | Cod sursa (job #946185) | Cod sursa (job #1313065) | Cod sursa (job #3272267)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define oo 2000000009
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<pair<int, int> > L[50002];
///nod, cost
int n, viz[50004], d[50002]; ///d[i] = costul minim pana la nodul i
int contor[50002]; //de cate ori am pus nodul i in coada
queue <int> q;
void Citire()
{
int x, y, c, m;
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> c;
L[x].push_back({ y, c });
}
}
void BellmanFord()
{
int i, x, c;
bool existNegative;
for (int i = 2; i <= n; i++)
d[i] = oo;
existNegative = false;
viz[1] = 1;
q.push(1);
contor[1] = 1;
while (!q.empty() && !existNegative)
{
x = q.front();
q.pop();
viz[x] = 0;
for (auto w : L[x])
{
i = w.first;
c = w.second;
if (d[i] > d[x] + c)
{
d[i] = d[x] + c;
if (viz[i] == 0)
{
if (contor[i] > n)
existNegative = true;
else
{
q.push(i);
viz[i] = 1;
contor[i]++;
}
}
}
}
}
if (existNegative)
fout << "Ciclu negativ!";
else
{
for (int i = 2; i <= n; i++)
fout << d[i] << " ";
fout << "\n";
}
}
int main()
{
Citire();
BellmanFord();
return 0;
}