Pagini recente » Cod sursa (job #2035996) | Cod sursa (job #2873487) | Cod sursa (job #1718927) | Cod sursa (job #1660794) | Cod sursa (job #3039710)
#include<iostream>
#include<fstream>
#include<set>
#include<algorithm>
#include<vector>
#include<queue>
#define inf 1e9
using namespace std;
int i, n, m, x, y, cost, d[50005], ok = 1, frec[50005], inq[50005];
struct muchie
{
int x;
int y;
int cost;
};
vector<muchie> muc[50005];
queue <int> q;
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[x].push_back(aux);
}
fill(d + 2, d + n + 1, inf);
q.push(1);
while(!q.empty())
{
int nod = q.front();
frec[nod]++;
inq[nod]=0;
if(frec[nod]>n)
{
cout << "Ciclu negativ!";
return 0;
}
q.pop();
for(auto v: muc[nod])
{
if(d[v.y]>d[nod] + v.cost)
{
d[v.y] = d[nod] + v.cost;
if(!inq[v.y]){
q.push(v.y);
inq[v.y]=1;
}
}
}
}
/*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] << " ";
}
}