Pagini recente » Cod sursa (job #492295) | Cod sursa (job #2750483) | Cod sursa (job #2633826) | Cod sursa (job #434123) | Cod sursa (job #2070600)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fi("bellmanford.in");
ofstream fo("bellmanford.out");
const int nmax=50000,INF=1<<30;
int n,m,best[nmax],updates[nmax],x,y,c;
vector <pair <int,int> > V[nmax];
queue <int> Q;
void bellmanford()
{
while(!Q.empty())
{
int x=Q.front();
Q.pop();
for(auto edge:V[x])
{
int y=edge.first;
int cost=edge.second;
if(cost+best[x]<best[y])
{
Q.push(y);
best[y]=cost+best[x];
updates[y]++;
if(updates[y]>=n)
return;
}
}
}
}
int main()
{
fi>>n>>m;
for(int i=1;i<=m;i++)
{
fi>>x>>y>>c;
V[x].push_back({y,c});
}
for(int i=1;i<=n;i++)
{
updates[i]=0;
best[i]=INF;
}
best[1]=0;
Q.push(1);
bellmanford();
for(int i=1;i<=n;i++)
if(updates[i]>=n)
{
fo<<"Ciclu negativ!\n";
fi.close();
fo.close();
return 0;
}
for(int i=2;i<=n;i++)
fo<<best[i]<<" ";
fi.close();
fo.close();
return 0;
}