Pagini recente » Cod sursa (job #2201804) | Cod sursa (job #1593379) | Cod sursa (job #2019113) | Cod sursa (job #2178924) | Cod sursa (job #2481633)
#include <bits/stdc++.h>
#define M 50005
#define INF INT_MAX-1
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n,m,d[M],v[M];
vector<pair<int,int> >lista[M];
deque<int>q;
bool inq[M];
void citire()
{
in>>n>>m;
for(int i=0;i<m;i++)
{
int x,y,c;
in>>x>>y>>c;
lista[x].push_back({y,c});
}
}
void bellman(int nod)
{
for(int i=1;i<=n;i++)
{
v[i]=0;
d[i]=INF;
}
d[nod]=0;
q.push_back(nod);
inq[nod]=true;
while(!q.empty())
{
int nodc=q.front();
v[nodc]++;
if(v[nodc]>n)
{
out<<"Ciclu negativ!";
return;
}
inq[nodc]=false;
q.pop_front();
for(auto x:lista[nodc])
{
int vecin=x.first;
int cost=x.second;
if(d[nodc]+cost<d[vecin])
{
d[vecin]=d[nodc]+cost;
if(!inq[vecin])
{
q.push_back(vecin);
inq[vecin]=true;
}
}
}
}
for(int i=2;i<=n;i++)
out<<d[i]<<' ';
}
int main()
{
citire();
bellman(1);
return 0;
}