Pagini recente » Cod sursa (job #792564) | Cod sursa (job #1704734) | Monitorul de evaluare | Cod sursa (job #2016975) | Cod sursa (job #1998176)
#include <bits/stdc++.h>
#define nmax 50001
#define oo LONG_MAX
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n,m,viz[nmax],d[nmax],cnt[nmax];
vector<pair<int,int> >h[nmax];
queue<int>c;
void Citire()
{
int i,x,y,cost;
fin>>n>>m;
for(i=1; i<=m; i++)
{
fin>>x>>y>>cost;
h[x].push_back({y,cost});
}
}
void Bellmanford()
{
int i,p,q,x;
bool gata;
for(i=1; i<=n; i++)
d[i]=oo;
d[1]=0;
c.push(1);
viz[1]=1;
gata=true;
while(!c.empty() && gata)
{
x=c.front();
viz[x]=0;
c.pop();
for(i=0; i<h[x].size(); i++)
{
p=h[x][i].first;
q=h[x][i].second;
if(d[p]>d[x]+q)
{
d[p]=d[x]+q;
if(!viz[p])
{
if(cnt[p]>n)
gata=false;
else
{
cnt[p]++;
viz[p]=1;
c.push(p);
}
}
}
}
}
if(!gata)
fout<<"Ciclu negativ\n";
else
{
for(i=2; i<=n; i++)
fout<<d[i]<<" ";
fout<<"\n";
}
}
int main()
{
Citire();
Bellmanford();
fin.close();
fout.close();
return 0;
}