Pagini recente » Cod sursa (job #2386154) | Cod sursa (job #1099195) | Cod sursa (job #2345433) | Cod sursa (job #1642324) | Cod sursa (job #2113857)
#include <fstream>
#include <vector>
#define inf 2000000000
#define nmax 50005
using namespace std;
fstream f1("bellmanford.in", ios::in);
fstream f2("bellmanford.out", ios::out);
int n, m, viz[nmax], nrit[nmax], prim, ultim, k, coada[nmax], d[nmax], ok;
vector <pair < int, int > > v[nmax];
void citire()
{
int i, x, y, c;
f1>>n>>m;
for(i=1; i<=m; i++)
{
f1>>x>>y>>c;
v[x].push_back(make_pair(y, c));
///v[y].push_back(make_pair(x, c));
}
}
void bell()
{
int i, nod, ct, vec;
prim=ultim=k=1;
coada[prim]=1;
d[1]=0;
viz[1]=1;
for(i=2; i<=n; i++)
d[i]=inf;
ok=1;
while((k!=0)&&(ok))
{
nod=coada[prim];
viz[nod]=0;
prim++;
if(prim> nmax-3) prim=1;
k--;
for(auto it=v[nod].begin();(it!=v[nod].end())&&ok; ++it)
{
vec=(*it).first;
ct=(*it).second;
if(d[vec]> ct+d[nod])
{
d[vec]=ct+d[nod];
if(!viz[vec])
{
viz[vec]=1;
ultim++;
if(ultim> nmax-3) ultim=1;
k++;
coada[ultim]=vec;
nrit[vec]++;
if(nrit[vec]> n) ok=0;
}
}
}
}
if(!ok) f2<<"Ciclu negativ!";
else
{
for(i=2; i<=n; i++)
f2<<d[i]<<' ';
}
}
int main()
{
citire();
bell();
return 0;
}