Pagini recente » Cod sursa (job #2950741) | Cod sursa (job #837706) | Cod sursa (job #1348497) | Cod sursa (job #2373508) | Cod sursa (job #2532863)
#include <bits/stdc++.h>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n,m,d[50005],x,y,z,inq[50005],cnt[50005];
vector<pair<int,int>> v[50005];
queue<int> q;
bool bellman(int nod)
{
inq[nod]=1;
q.push(nod);
d[nod]=0;
while(!q.empty())
{
int x=q.front();
q.pop();
inq[x]=0;
for(auto it:v[x])
{
if(d[it.first]>d[x]+it.second)
{
d[it.first]=d[x]+it.second;
cnt[it.first]++;
if(cnt[it.first]>n-1) return 0;
if(!inq[it.first])
{
inq[it.first]=1;
q.push(it.first);
}
}
}
}
return 1;
}
int main()
{
in>>n>>m;
for(int i=1;i<=m;i++)
{
in>>x>>y>>z;
v[x].push_back({y,z});
}
for(int i=1;i<=n;i++) d[i]=1e6;
if(bellman(1)) for(int i=2;i<=n;i++) out<<d[i]<<" ";
else out<<"Ciclu negativ!";
return 0;
}