Pagini recente » Cod sursa (job #563996) | Cod sursa (job #1446514) | Cod sursa (job #2024740) | Cod sursa (job #432896) | Cod sursa (job #1650131)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <algorithm>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int nmax = 5e4+5;
const int oo = (1<<30);
vector <pair<int,int> > g[nmax];
int dist[nmax], cnt[nmax], n;
bool bellman(int start)
{
vector <pair<int,int> > :: iterator it;
queue <int> q;
bitset <nmax> viz=0;
int dad, son, cost;
fill(dist+1, dist+n+1, oo);
dist[start]=0;
q.push(start);
while(!q.empty())
{
dad=q.front();
viz[dad]=false;
q.pop();
for(it=g[dad].begin(); it!=g[dad].end(); it++)
{
son=it->first;
cost=it->second;
if(dist[son] > dist[dad]+cost)
{
dist[son]=dist[dad]+cost;
if(viz[son]==false)
{
viz[son]=true;
cnt[son]++;
q.push(son);
if(cnt[son] > n) return true;
}
}
}
}
return false;
}
int main()
{
ios_base::sync_with_stdio(false);
int m, 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 cycle=bellman(1);
if(cycle==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;
}