Pagini recente » Cod sursa (job #597537) | Cod sursa (job #3225243) | Cod sursa (job #2667094)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector < pair<int, int> >v[50005];
int n, m, x, y, c, viz[50005], in[50005], dist[500005];
queue <int> q;
int bellman(int nod)
{
for(int i=1; i<=n; i++) dist[i]=250000000;
dist[nod]=0;
q.push(nod);
while(!q.empty())
{
nod=q.front();
q.pop();
in[nod]=0;
viz[nod]++;
if(viz[nod]>=n) return 0;
for(int i=0; i<v[nod].size(); i++)
if(dist[v[nod][i].first]>dist[nod]+v[nod][i].second)
{
dist[v[nod][i].first]=dist[nod]+v[nod][i].second;
if(in[v[nod][i].first]==0)
{
q.push(v[nod][i].first);
in[v[nod][i].first]=1;
}
}
}
}
int main()
{
fin >> n >> m;
for(int i=1; i<=m; i++)
{
fin >> x >> y >> c;
v[x].push_back(make_pair(y, c));
}
if(bellman(1)) for(int i=2; i<=n; i++) fout << dist[i] << " ";
else fout << "Ciclu negativ!";
return 0;
}