Pagini recente » Cod sursa (job #2796765) | Cod sursa (job #534668) | Cod sursa (job #263747) | Cod sursa (job #2048293) | Cod sursa (job #1536622)
#include<cstdio>
#include<vector>
#define inf 0x3f3f3f3f
#include<queue>
using namespace std;
vector< pair<int,int> >g[50002];
queue<int> q;
int ap[50002],best[50002],i,n,x,y,z,m,next,crt;
bool inq[50002];
int main()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
g[x].push_back({y,z});
}
for(i=1;i<=n;i++)
{
best[i]=inf;
}
best[1]=0;
inq[1]=true;
q.push(1);
while(!q.empty())
{
crt=q.front();
q.pop();
inq[crt]=false;
for(i=0;i<g[crt].size();i++)
{
next=g[crt][i].first;
if(best[next]>best[crt]+g[crt][i].second)
{
best[next]=best[crt]+g[crt][i].second;
if(!inq[next])
{
inq[next]=true;
q.push(next);
ap[next]++;
if(ap[next]>n)
{
printf("Ciclu negativ!\n");
return 0;
}
}
}
}
}
for(i=2;i<=n;i++)
{
printf("%d ",best[i]);
}
return 0;
}