Pagini recente » Cod sursa (job #1187227) | Cod sursa (job #1665833) | Cod sursa (job #916851) | Cod sursa (job #1546258) | Cod sursa (job #1816133)
#include <iostream>
#include<fstream>
#include<queue>
#define inf 100000000
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,i,cst[250001],v[50001],j;
vector<int>q;
bool ok;
struct muchie
{
int x,y;
};
muchie c[250001];
int functie(int i,int j,int c)
{
if(v[j]>v[i]+c)
{
v[j]=v[i]+c;
//parrent[j]=i;
return 1;
}
return 0;
}
void sterge(int j)
{
swap(q[j],q[q.size()-1]);
q.pop_back();
}
int main()
{
f>>n>>m;
q.push_back(0);
for(i=1;i<=m;i++)
{
f>>c[i].x>>c[i].y>>cst[i];
if(c[i].x==1)
q.push_back(i);
}
v[1]=0;
for(i=2;i<=n;i++)
v[i]=inf;
for(i=1;i<n;i++)
for(j=1;j<q.size();j++)
{
if(functie(c[j].x,c[j].y,cst[j]))
{
q.push_back(j);
}
else
{
sterge(j);
}
}
ok=1;
for(j=1;j<=m && ok;j++)
{
int x1=v[c[j].y];
if(functie(c[j].x,c[j].y,cst[j]))
g<<"Ciclu negativ!",ok=0,v[c[j].y]=x1;
}
if(ok)
for(i=2;i<=n;i++)
g<<v[i]<<' ';
}