Pagini recente » Istoria paginii runda/concurs_freshmen_2/clasament | Monitorul de evaluare | Istoria paginii runda/simulare_de_oni_9/clasament | test41241 | Cod sursa (job #2333025)
#include <vector>
#include <fstream>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct arc{
int vf;
int c;
};
vector <arc> x[50001];
queue <int> q;
int d[50001], inqueue[50001],up[50001];
int main()
{
int n,m,a,b,c,i,k,v,w;
fin>>n>>m;
for(i=1;i<=m;i++)
{
fin>>a>>b>>c;
x[a].push_back({b,c});
}
for(i=1;i<=n;i++)
{
d[i]=1000000000;
}
d[1]=0;
q.push(1);
inqueue[1]=1;
up[1]++;
int negativ=0,cost;
while(q.empty()!=1 && negativ==0)
{
v=q.front();
q.pop();
inqueue[v]=0;
k=x[v].size();
for(i=0;i<k;i++)
{
w=x[v][i].vf;
cost=x[v][i].c;
if(d[v]+cost<d[w])
{
d[w]=d[v]+cost;
up[w]++;
if(up[w]>n-1)
negativ=1;
if(inqueue[w]==0)
{
inqueue[w]=1;
q.push(w);
}
}
}
}
if(negativ==1)
fout<<"Ciclu negativ!";
else
{
for(i=2;i<=n;i++)
fout<<d[i]<<" ";
}
return 0;
}