Pagini recente » Cod sursa (job #483260) | Cod sursa (job #903285) | Cod sursa (job #614614) | Cod sursa (job #2394085) | Cod sursa (job #1096339)
/* Algortimul lui Bellman Ford
Complexitate O(m*n)
*/
#include <cstdio>
#include <algorithm>
#include<vector>
#include<queue>
using namespace std;
int nod,minim,i,aux,n,k,j,p,s,unu,t,m,doi,x,st,dr,maxi,sol,maxi2,viz[50010],y,conex,cost,d[50010],ok;
vector < pair<int, int> > v[50010];
bool negative;
bool inside[50010];//verificam daca un nod este deja introdus in coada
int nr[50010];//nr de cate ori a fost introdus un nod in coada
queue <int> q;
void bellman()
{
while(! q.empty())
{
nod=q.front();
inside[nod]=false;
q.pop();
//printf("%d\n",nod);
for(i=0;i<v[nod].size();i++)
{
if(d[v[nod][i].first] > d[nod]+v[nod][i].second)
{
d[v[nod][i].first] = d[nod]+v[nod][i].second;
if(inside[v[nod][i].first] == false)
{
q.push(v[nod][i].first);
inside[v[nod][i].first]=true;
nr[v[nod][i].first]++;
if(nr[v[nod][i].first]++ > n)
{
negative=true;
return;
}
}
}
}
}
}
int main()
{
freopen ("bellmanford.in","r",stdin);
freopen ("bellmanford.out","w",stdout);
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++)
{
scanf("%d %d %d",&x,&y,&cost);
v[x].push_back(make_pair(y,cost));
}
for(i=2;i<=n;i++)
{
d[i]=100000000;
}
q.push(1);
nr[1]++;
inside[1]=true;
bellman();
if(negative ==true)
{
printf("Ciclu negativ!");
}
else{
for(i=2;i<=n;i++)
{
if(d[i]==100000000)
printf("0 ");
else
printf("%d ",d[i]);
}
}
}