Pagini recente » Cod sursa (job #3170686) | Cod sursa (job #2493615) | Cod sursa (job #3277113) | Cod sursa (job #558053) | Cod sursa (job #1119115)
# include <iostream>
# include <fstream>
# include <vector>
# include <queue>
# include <string.h>
# define nmax 50002
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int dist[nmax], apar[nmax], n, m;
queue <int> q;
vector < pair <int, int> > a[nmax];
bool inq[nmax];
int main()
{
int i, x, y, c;
f>>n>>m;
for(i=1; i<=m; i++)
{
f>>x>>y>>c;
a[x].push_back(make_pair(y,c));
}
memset(dist, '5', sizeof(dist));
memset(inq, false, sizeof(inq));
dist[1]=0;
q.push(1);
int nod;
bool neg_cycle=false;
vector < pair <int, int> > :: iterator it;
while(!q.empty())
{
nod=q.front();
q.pop();
inq[nod]=false;
for(it=a[nod].begin(); it!=a[nod].end(); ++it)
{
if(dist[it->first] > dist[nod] + it->second)
{
dist[it->first] = dist[nod] + it->second;
if(!inq[it->first])
{
if(apar[it->first] > n)
{
neg_cycle=true;
break;
}
else
{
q.push(it->first);
apar[it->first]+=1;
inq[it->first]=true;
}
}
}
}
}
if(neg_cycle)
g<<"Ciclu negativ!";
else
{
for(i=2; i<=n; i++)
g<<dist[i]<<" ";
}
return 0;
}