Pagini recente » Solutii preONI 2008, Runda 3 | Cod sursa (job #2074558) | Cod sursa (job #403820) | Cod sursa (job #3869) | Cod sursa (job #2147196)
#include <fstream>
#define MAXn 50001
#define MAXm 250001
#define inf 1<<30
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
struct nod{int val,cost; nod*urm;}*v[MAXn],*r;
int n,m,p,u;
int d[MAXn];
bool viz[MAXn];
bool e_pus[MAXn];
bool ciclu_negativ=false;
int c[MAXm*2];
void BF(){
for(int i=1 ; i<=n ; ++i)
d[i]=inf;
p=u=1;
c[1]=1;
e_pus[1]=true;
d[1]=0;
int x;
while(p<=u)
{
x=c[p];
++p;
viz[x]++;
if(viz[x]==n)
{
ciclu_negativ=true;
return ;
}
r=v[x];
while(r!=0)
{
int vec=r->val;
int cost=r->cost;
if(d[vec]>d[x]+cost)
{d[vec]=d[x]+cost;
if(e_pus[vec]==0)
{
e_pus[vec]=1;
c[++u]=vec;
}}
r=r->urm;
}
e_pus[x]=0;
}
}
void af(){
for(int i=2 ; i<=n ; ++i)
g<<d[i]<<" ";
g<<'\n';
}
int main()
{
f>>n>>m;
int x,y,z;
for(int i=1 ; i<=m ; ++i)
{
f>>x>>y>>z;
nod*q;
q=new nod;
q->val=y;
q->cost=z;
q->urm=v[x];
v[x]=q;
}
BF();
if(ciclu_negativ)
g<<"Ciclu negativ!"<<'\n';
else
af();
return 0;
}