Pagini recente » Cod sursa (job #2959005) | Cod sursa (job #3191337) | Cod sursa (job #2206966) | Cod sursa (job #1604492) | Cod sursa (job #2034056)
#include <bits/stdc++.h>
using namespace std;
const int nmax=50001;
queue<int>c;
vector<pair<int,int> >L[nmax];
int n,m,dist[nmax],f[nmax];
bool viz[nmax];
///Complexitate O(n^2)
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
inline void BF()
{
int x;
bool ok=true;
for(int i=1;i<=n;i++)
dist[i]=(1<<30);
dist[1]=0;
c.push(1);
viz[1]=true;
while(!c.empty() && ok)
{
x=c.front();
c.pop();
viz[x]=false;
for(int i=0;i<L[x].size();i++)
{
int p,q;
p=L[x][i].first;
q=L[x][i].second;
if(dist[p]>dist[x]+q)
{
dist[p]=dist[x]+q;
if(!viz[p])
{
if(f[p]>n)
ok=false;
else
{
f[p]++;
viz[p]=1;
c.push(p);
}
}
}
}
}
if(!ok)
fout<<"Ciclu negativ!\n";
else
{
for(int i=2;i<=n;i++)
fout<<dist[i]<<" ";
fout<<"\n";
}
}
int main()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
{
int nod,nod1,cost;
fin>>nod>>nod1>>cost;
L[nod].push_back({nod1,cost});
}
BF();
fin.close();
fout.close();
return 0;
}