Pagini recente » Cod sursa (job #442917) | Cod sursa (job #605422) | Cod sursa (job #2600591) | Cod sursa (job #102657) | Cod sursa (job #2356479)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define nmax 50005
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m, s[nmax], d[nmax];
vector <pair<int,int> > v[nmax];
queue <int> q;
void citire()
{
int i,x,y,c;
f>>n>>m;
for(i=1; i<=m; i++)
{
f>>x>>y>>c;
v[x].push_back({y,c});
}
}
void afis()
{
int i,j;
for(i=1; i<=n; i++)
{for(j=0; j<v[i].size(); j++)
cout<< v[i][j].first <<" ";
cout<<endl;}
}
int bellman()
{
int nod, next, cst,i;
for(i=2; i<=n; i++)
d[i]=1e9;
q.push(1);
s[1]=1;
while(!q.empty())
{
nod=q.front();
s[nod]=0; //nu mai e in coada
q.pop();
for(i=0; i<v[nod].size(); i++)
{
next=v[nod][i].first;
cst=v[nod][i].second;
if(cst+d[nod]<d[next] && s[next]==0)
{d[next]=d[nod]+cst; q.push(next); s[next]=1;}
}
}
return 1;
}
int main()
{
citire();
//afis();
if(bellman())
for(int i=2; i<=n; i++)
g<<d[i]<<" ";
else
g<<"Ciclu negativ!";
f.close();
g.close();
return 0;
}