Pagini recente » Cod sursa (job #516511) | Cod sursa (job #2575455) | Cod sursa (job #893697) | Cod sursa (job #2806156) | Cod sursa (job #2302850)
#include <iostream>
#include <fstream>
#include <climits>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int dp[50005],ok[50005], cnt[50005],n,m;
vector< pair<int, int> >G[50005];
queue <int> Q;
void citire()
{
fin>>n>>m;
for(int i=1; i<=m; i++)
{
int x,y,c;
fin>>x>>y>>c;
G[x].push_back({y,c});
}
for(int i=2; i<=n; i++)
dp[i]=INT_MAX/2;
}
int neg=0;
void bellman()
{
dp[1]=0;
Q.push(1);
ok[1]=1;
cnt[1]++;
while(!Q.empty()&&neg==0)
{
int x=Q.front();
Q.pop();
ok[x]=0;
for(auto &v:G[x])
{
int y=v.first;
int cost=v.second;
if(dp[y]>dp[x]+cost)
{
dp[y]=dp[x]+cost;
if(ok[y]==0)
{
Q.push(y);
ok[y]=1;
cnt[y]++;
if(cnt[y]>n)
neg=1;
}
}
}
}
}
void afish()
{ if(neg==0)
for(int i=2; i<=n; i++)
fout<<dp[i]<<" ";
else
fout<<"Ciclu negativ!";
}
int main()
{
citire();
bellman();
afish();
return 0;
}