Pagini recente » Cod sursa (job #1555147) | Cod sursa (job #2262941) | Cod sursa (job #453223) | Cod sursa (job #2267268) | Cod sursa (job #2485477)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
queue <int> Q;
vector <pair<int,int>> G[50005];
int n,m,x,y,cost,i,d[50005],nr[50005];
bool sel[50005];
bool bellmanford(){
for(int i=1; i<=n; ++i)sel[i]=false,d[i]=INT_MAX;
sel[1]=true;
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;
else 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>>cost;
G[x].push_back({cost,y});
}
if(bellmanford())g<<"Ciclu negativ!\n";
else for(i=2; i<=n; ++i)g<<d[i]<<' ';
return 0;
}