Pagini recente » Cod sursa (job #1107518) | Cod sursa (job #2282043) | Cod sursa (job #2289197) | Cod sursa (job #2227892) | Cod sursa (job #1590568)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int nmax = 50005;
const int oo = (1<<29);
vector <pair<int,int> > g[nmax];
int n, m, dist[nmax], nr[nmax];
bool bellman()
{
vector <pair<int,int> >::iterator it;
queue <int> q;
int dad, son,cost, i;
for(i=2; i<=n; i++)
dist[i]=oo;
q.push(1);
while(!q.empty())
{
dad=q.front();
q.pop();
for(it=g[dad].begin(); it!=g[dad].end(); it++)
{
son=it->first;
cost=it->second;
if(dist[dad]+cost < dist[son])
{
dist[son]=dist[dad]+cost;
nr[son]++;
q.push(son);
if(nr[son] > n) return true;
}
}
}
return false;
}
int main()
{
ios_base::sync_with_stdio(false);
int i, x, y, c;
fin >> n >> m;
for(i=1; i<=m; i++)
{
fin >> x >> y >> c;
g[x].push_back(make_pair(y, c));
}
bool negative=bellman();
if(negative==true) fout << "Ciclu negativ!";
else for(i=2; i<=n; i++)
{
if(dist[i]==oo) dist[i]=0;
fout << dist[i] << " ";
}
fin.close();
fout.close();
return 0;
}