Pagini recente » Cod sursa (job #1835382) | Cod sursa (job #1559354) | Cod sursa (job #2135012) | Cod sursa (job #1886360) | Cod sursa (job #2965006)
#include <bits/stdc++.h>
#include <fstream>
#define cin fin
#define cout fout
#define oo 1<<30
using namespace std;
ifstream cin ("bellmanford.in");
ofstream cout("bellmanford.out");
int n,i,j,k,l,m,a,b,c,cost[50008],repetitie[50008],i2,ok;
struct compar
{
bool operator()(int a, int b)
{
return cost[a]>cost[b];
}
};
vector<pair<int,int>>G[50008];
queue<int>Q;
void bellman(int nod);
int main()
{
cin>>n>>m;
for(i=1;i<=m;i++)
{
cin>>a>>b>>c;
G[a].push_back({b,c});
}
bellman(1);
if(ok==1)
cout<<"Ciclu negativ!";
else
for(i=2;i<=n;i++)
{
cout<<cost[i]<<" ";
}
return 0;
}
void bellman(int nod)
{
for(int i=1;i<=n;i++)
{
cost[i]=oo;
}
cost[nod]=0;
Q.push(nod);
while(!Q.empty())
{
k=Q.front();
Q.pop();
repetitie[k]++;
if(repetitie[k]>=n)
{
ok=1;
break;
}
for(auto i:G[k])
{
if(cost[i.first]>cost[k]+i.second)
{
cost[i.first]=cost[k]+i.second;
Q.push(i.first);
}
}
}
}