Pagini recente » Cod sursa (job #2848862) | Cod sursa (job #61195) | Cod sursa (job #219755) | Cod sursa (job #1072711) | Cod sursa (job #1851612)
#include <bits/stdc++.h>
# define INF 0x3f3f3f3f
#define nmax 50002
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,x,y,cost,ok,dist[nmax],nr,viz[nmax];
vector< pair<int, int> > v[nmax];
queue<int> c;
int main()
{
f>>n>>m;
for(int i=1;i<=m;i++)
{
f>>x>>y>>cost;
v[x].push_back(make_pair(y,cost));
}
memset(dist,INF,sizeof(dist));
dist[1]=0;
c.push(1);
while(!c.empty())
{
nr=c.front();
c.pop();
viz[nr]++;
if(viz[nr]==n)
{
g<<"Ciclu negativ!"<<'\n';
ok=1;
break;
}
for(int i=0;i<v[nr].size();i++)
if(dist[v[nr][i].first]>dist[nr]+v[nr][i].second)
{
dist[v[nr][i].first]=dist[nr]+v[nr][i].second;
c.push(v[nr][i].first);
}
}
if(!ok)
{
for(int i=2;i<=n;i++)
if(dist[i]==INF) g<<"0"<<" ";
else g<<dist[i]<<" ";
g<<'\n';
}
return 0;
}