Pagini recente » Cod sursa (job #2753955) | Cod sursa (job #933255) | Cod sursa (job #3189769) | Cod sursa (job #1021775) | Cod sursa (job #2499050)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
const int INF=0x3f3f3f3f;
queue <int> q;
vector <pair<int,int>> G[50005];
int n,m,x,y,c,i,d[50005],nr[50005];
bool sel[50005];
bool Bellmanford()
{ for(int i=1; i<=n; i++)
{ d[i]=INF;
sel[i]=false;
}
sel[1]=true;
nr[1]=1;
q.push(1);
d[1]=0;
bool done=false;
while(!q.empty() && !done)
{ x=q.front();
q.pop();
sel[x]=false;
for(auto it : G[x])
{ if(nr[it.second]>n)
done=true;
if(d[x]+it.first<d[it.second])
{ d[it.second]=d[x]+it.first;
if(!sel[it.second])
{ q.push(it.second);
sel[it.second]=true;
}
nr[it.second]=nr[x]+1;
if(nr[it.second]>n)
done=true;
}
}
}
return done;
}
int main()
{ f>>n>>m;
for(i=1; i<=m; ++i)
{ f>>x>>y>>c;
G[x].push_back({c,y});
}
if(Bellmanford())
g<<"Ciclu negativ!"<<'\n';
else
for(i=2; i<=n; i++)
g<<d[i]<<' ';
return 0;
}