Pagini recente » Cod sursa (job #713812) | Cod sursa (job #328096) | Cod sursa (job #930392) | Cod sursa (job #1834445) | Cod sursa (job #384654)
Cod sursa(job #384654)
#include<stdio.h>
#include<algorithm>
#include<queue>
#define INF 20000001
#define Nmx 50002
int n,m,viz[Nmx],cost[Nmx];
int nr;
using namespace std;
queue<int>Q;
struct nod
{
int inf;
int cost;
nod *urm;
};
nod *G[Nmx];
void add(int x,int y,int c)
{
nod *aux=new nod;
aux->inf=y;
aux->cost=c;
aux->urm=G[x];
G[x]=aux;
}
void citire()
{
int x,y,c;
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i)
{
scanf("%d%d%d",&x,&y,&c);
add(x,y,c);
}
}
void afisare()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
int x,y,c;
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i)
{
scanf("%d%d%d",&x,&y,&c);
if(cost[x]+c<cost[y])
{
printf("Ciclu negativ!\n");
return ;
}
}
for(int i=2;i<=n;++i)
printf("%d ",cost[i]);
}
void solve()
{
int st;
for(int i=2;i<=n;++i)
cost[i]=INF;
viz[1]=1;
Q.push(1);
long long pas=0;
while(!Q.empty()&&pas<=n*m*1LL)
{
pas++;
st=Q.front();
viz[st]=0;
for(nod *p=G[st];p;p=p->urm)
if(cost[st]+p->cost<cost[p->inf])
{
cost[p->inf]=cost[st]+p->cost;
if(!viz[p->inf])
{
viz[p->inf]=1;
Q.push(p->inf);
}
}
Q.pop();
}
afisare();
}
int main()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
citire();
solve();
return 0;
}