Pagini recente » Cod sursa (job #2816634) | Cod sursa (job #3147418) | Cod sursa (job #2212041) | Cod sursa (job #1917700) | Cod sursa (job #2378836)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int INF=1000000001;
const int N=10001;
int n,m,d[N],nrq[N];
bool inq[N];
queue <int> q;
vector <pair<int,int>> a[N];
void citire()
{
int x,y,c;
in>>n>>m;
for(int i=1; i<=m; ++i)
{
in>>x>>y>>c;
a[x].push_back(make_pair(y,c));
}
}
void bellman_ford(int x)
{
for(int i=1; i<=n; ++i) d[i]=INF;
q.push(x);
d[x]=0;
inq[x]=true;
nrq[x]++;
while(!q.empty())
{
x=q.front();
q.pop();
int y,c;
for(auto p: a[x])
{
y=p.first;
c=p.second;
if(d[x]+c<d[y])
{
d[y]=d[x]+c;
if(!inq[y])
{
q.push(y);
inq[y]=true;
nrq[y]++;
if(nrq[y]==n)
{
out<<"Ciclu negativ";
return ;
}
}
}
}
}
}
int main()
{
citire();
bellman_ford(1);
for(int i=2; i<=n; ++i) out<<d[i]<<" ";
return 0;
}