Pagini recente » Cod sursa (job #1011898) | Cod sursa (job #2091297) | Cod sursa (job #1691730) | Cod sursa (job #2184891) | Cod sursa (job #2030397)
#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int,int>ii;
vector<ii>g[50001];
queue<int>q;
int dist[50001],nr[50001];
bool inq[50001];
const int inf=300000000;
int main()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
int n,m,nc=0,x,y,z,i,val;
scanf("%d%d",&n,&m);
for(i=1;i<=m;++i)
{
scanf("%d%d%d",&x,&y,&z);
g[x].push_back(ii(y,z));
}
q.push(1);
inq[1]=1;
for(i=2;i<=n;++i)
{
dist[i]=inf;
}
while(!q.empty()&&!nc)
{
val=q.front();
q.pop();
inq[val]=0;
if(dist[val]<inf)
{
for(i=0;i<g[val].size();++i)
{
if(dist[g[val][i].first]>dist[val]+g[val][i].second)
{
dist[g[val][i].first]=dist[val]+g[val][i].second;
if(!inq[g[val][i].first])
{
if(nr[g[val][i].first]>n)
nc=1;
else
{
q.push(g[val][i].first);
inq[g[val][i].first]=1;
nr[g[val][i].first]++;
}
}
}
}
}
}
if(nc)
printf("Ciclu negativ!\n");
else
{
for(i=2;i<=n;++i)
{
printf("%d ",dist[i]);
}
}
return 0;
}