Pagini recente » Cod sursa (job #2159080) | Cod sursa (job #469634) | Cod sursa (job #1758433) | Cod sursa (job #2372180) | Cod sursa (job #2502117)
#include <fstream>
#include <queue>
#include <vector>
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,c,i,d[50005],nr[50005];
int sel[50005];
int Bellmanford()
{
int i,ok=0;
for(i=1; i<=n; i++)
{ d[i]=50000000;
sel[i]=0;
}
sel[1]=1;
nr[1]=1;
q.push(1);
d[1]=0;
while(!q.empty() && !ok)
{ x=q.front();
q.pop();
sel[x]=0;
for(auto it : G[x])
{ if(nr[it.second]>n)
ok=1;
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]=1;
}
nr[it.second]=nr[x]+1;
if(nr[it.second]>n)
ok=1;
}
}
}
return ok;
}
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;
}