Pagini recente » Cod sursa (job #850445) | Cod sursa (job #1107185) | Cod sursa (job #2474778) | Cod sursa (job #2560148) | Cod sursa (job #2837462)
#include <bits/stdc++.h>
#define oo 2000000001
using namespace std;
/**
*/
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
/// nod, cost
vector< pair<int, int> > L[50002];
int viz[50002]; /// viz[i]=1 daca nodul i este pus in coada
int n, d[50002]; /// d[i] = costul minim pana la nodul i
int contor[50002]; /// numar de cate ori am pus nodul i
/// in coada
queue<int> q;
void Citire()
{
int i, x, y, c, m;
fin >> n >> m;
for (i = 1; i <= m; i++)
{
fin >> x >> y >> c;
L[x].push_back({y, c});
}
}
void BellmanFord()
{
bool existaNegative;
int i, x, c;
/// initializari:
for (i = 2; i <= n; i++)
d[i] = oo;
existaNegative = false;
viz[1] = 1;
q.push(1);
contor[1] = 1;
while (!q.empty() && !existaNegative)
{
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) existaNegative = true;
else
{
q.push(i);
viz[i] = 1;
contor[i]++;
}
}
}
}
}
if (existaNegative) fout << "Ciclu negativ!\n";
else
{
for (i = 2; i <= n; i++)
fout << d[i] << " ";
fout << "\n";
}
}
int main()
{
Citire();
BellmanFord();
fout.close();
return 0;
}