Pagini recente » Cod sursa (job #2182771) | Cod sursa (job #2248768) | Cod sursa (job #561907) | Istoria paginii utilizator/nenciugeorgel8b | Cod sursa (job #1539686)
#include <bits/stdc++.h>
#define infinit 1000000000
using namespace std;
struct muchie{
int nod,cost;
};
int n,m,d[50003],contor[50003];
bool viz[50003];
vector<muchie> L[50003];
queue<int> q;
inline void Citire()
{
int i,x;
muchie w;
ifstream fin("bellmanford.in");
fin>>n>>m;
for(i=1;i<=m;++i)
{
fin>>x>>w.nod>>w.cost;
L[x].push_back(w);
}
fin.close();
}
inline void BellmanFord()
{
int i,x,c;
unsigned int k;
bool AreCircuiteNegative;
muchie w;
//init
AreCircuiteNegative=false;
for(i=2;i<=n;++i) d[i]=infinit;
d[1]=0;
viz[1]=true;
q.push(1);
while(!q.empty() && !AreCircuiteNegative)
{
x=q.front();
q.pop();
viz[x]=false;
for(k=0;k<L[x].size();++k)
{
w=L[x][k];
i=w.nod;
c=w.cost;
if(d[x]<infinit)
if(d[i]>d[x] + c)
{
d[i]=d[x]+c;
if(!viz[i])
{
if(contor[i]>n)
AreCircuiteNegative=true;
else
{
q.push(i);
viz[i]=true;
contor[i]++;
}
}
}
}
}
ofstream fout("bellmanford.out");
if(!AreCircuiteNegative)
for(i=2;i<=n;++i) fout<<d[i]<<" ";
else fout<<"Ciclu negativ!";
fout<<"\n";
fout.close();
}
int main()
{
Citire();
BellmanFord();
return 0;
}