Pagini recente » Profil teapa | Cod sursa (job #343724) | Cod sursa (job #2764217) | Cod sursa (job #887531) | Cod sursa (job #2199828)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
const int N = 50010;
const int oo = 500000010;
int n,m,x,y,c,i,d[N],cnt[N];
vector<pair<int,int>> v[N];
queue<int> q;
bool Q[N];
int main()
{
f>>n>>m;
for(;m;m--)
{
f>>x>>y>>c;
v[x].push_back(make_pair(y,c));
}
for(i=1;i<=n;i++)
d[i]=oo;
d[1]=0;
q.push(1);
Q[1]=true;
while(q.size())
{
x=q.front();
q.pop();
Q[x]=false;
for(auto it:v[x])
{
y=it.first;
c=it.second;
if(d[y]>d[x]+c)
{
d[y]=d[x]+c;
if(!Q[y])
{
cnt[y]++;
if(cnt[y]==n)
{
g<<"Ciclu negativ!";
return 0;
}
q.push(y);Q[y]=true;}
}
}
}
for(i=2;i<=n;i++)
g<<d[i]<<' ';
return 0;
}