Pagini recente » Cod sursa (job #112268) | Cod sursa (job #1557382) | Cod sursa (job #987534) | Cod sursa (job #1739411) | Cod sursa (job #1918982)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define Nmax 50010
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,INF=1<<29;
int dist[Nmax],inQueue[Nmax],nr[Nmax];
vector <pair<int,int> > adj[Nmax];
queue <int> q;
int bellman()
{
for(int i=1;i<=n;i++)
dist[i]=INF;
dist[1]=0;
q.push(1);
int v,w,cost;
while(!q.empty())
{
v=q.front();
q.pop();
inQueue[v]=0;
for(int i=0;i<adj[v].size();i++)
{
w=adj[v][i].second;
cost=adj[v][i].first;
if(dist[w]>dist[v]+cost)
{
dist[w]=dist[v]+cost;
if(!inQueue[w])
{
if(nr[w]>=n+2)
return 0;
inQueue[w]=1;
nr[w]++;
q.push(w);
}
}
}
}
return 1;
}
int main()
{
f >> n >> m;
int x,y,c;
for(int i=0;i<m;i++)
{
f >> x >> y >> c;
adj[x].push_back(make_pair(c,y));
}
if(bellman())
{
for(int i=2;i<=n;i++)
g << dist[i] << " ";
} else g << "Ciclu negativ!\n";
return 0;
}