Pagini recente » Cod sursa (job #2982485) | Cod sursa (job #2928826) | Cod sursa (job #835980) | Rating David Malutan (Vincent47) | Cod sursa (job #3039688)
#include<iostream>
#include<fstream>
#include<set>
#include<algorithm>
#include<vector>
#define inf 1e9
using namespace std;
int i, n, m, x, y, cost, d[50005], ok=1;
struct muchie
{
int x;
int y;
int cost;
};
muchie muc[250005];
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
cin >> n >> m;
for(int i = 1; i <= m; i++)
{
cin >> x >> y >> cost;
muchie aux;
aux.x = x;
aux.y = y;
aux.cost = cost;
muc[i] = aux;
}
fill(d + 2, d + n + 1, inf);
for(int i = 1; i <= n&& ok; i++)
{
ok =0;
for(int j = 1; j <= m; j++)
{
int x = muc[j].x;
int y = muc[j].y;
int cost = muc[j].cost;
if(d[y] > d[x] + cost){
d[y] = min(d[y], d[x] + cost);
ok=1;
}
}
}
for(int j = 1; j <= m; j++)
{
int x = muc[j].x;
int y = muc[j].y;
int cost = muc[j].cost;
if(d[y] > d[x] + cost)
{
cout << "Ciclu negativ!";
return 0;
}
}
for(int i = 2; i <= n; i++)
{
if(d[i] == inf)
cout << 0 << " ";
else
cout << d[i] << " ";
}
}