Pagini recente » Cod sursa (job #478298) | Cod sursa (job #2372375) | Cod sursa (job #1711634) | Cod sursa (job #2755920) | Cod sursa (job #2545260)
#include <bits/stdc++.h>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n,m,x,y,c,inq[50005],cnt[50005],ok,d[50005];
vector<pair<int,int>> v[50005];
queue<int> q;
void bellman(int nod)
{
for(int i=1;i<=n;i++) d[i]=1e9;
q.push(nod);
inq[nod]=1;
d[nod]=0;
while(!q.empty())
{
x=q.front();
inq[x]=0;
q.pop();
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) {
ok=0;
return;
}
if(!inq[it.first])
{
q.push(it.first);
inq[it.first]=1;
}
}
}
}
int main()
{
in>>n>>m;
for(int i=1;i<=n;i++)
{
in>>x>>y>>c;
v[x].push_back({y,c});
}
ok=1;
bellman(1);
if(ok) for(int i=2;i<=n;i++) out<<d[i]<<" ";
else out<<"Ciclu negativ!";
return 0;
}