Pagini recente » Cod sursa (job #968433) | Cod sursa (job #1400678) | Cod sursa (job #1156300) | Cod sursa (job #313910) | Cod sursa (job #2723354)
#include <fstream>
#include <math.h>
#include <set>
#include <queue>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
unsigned long long k;
int dist[50001], n, m, f[50001], cnt[50001];
vector <pair <int, int>> l[50001];
int bellman_ford(int nod)
{
int i, p, u, nod2, ok = 1, nod1, c;
queue <int> coada;
for (i = 1; i<= n; i++)
dist[i] = 1e9;
coada.push(nod);
f[nod] = 1;
cnt[nod] = 1;
dist[nod] = 0;
while (coada.size() != 0)
{
nod1 = coada.front();
f[nod1]++;
for (i = 0; i< l[nod1].size(); i++)
{
nod2 = l[nod1][i].first;
c = l[nod1][i].second;
if(dist[nod1] + c < dist[nod2])
{
dist[nod2] = dist[nod1] + c;
if(f[nod2] == 0)
{
coada.push(nod2);
f[nod2] = 1;
cnt[nod2]++;
if(cnt[nod2] > n)
return 0;
}
}
}
f[nod1] = 0;
coada.pop();
}
return 1;
}
int main()
{
int x, y, c, i;
fin >> n >> m;
for (i =1; i<= m; i++)
{
fin >> x >> y >> c;
l[x].push_back({y, c});
}
if (bellman_ford(1) == 0)
{
fout << "Ciclu negativ!";
return 0;
}
else
{
for (i = 2; i<= n; i++)
fout << dist[i] << " ";
}
}