Pagini recente » Cod sursa (job #1053144) | Cod sursa (job #1512152) | Cod sursa (job #2421134) | Cod sursa (job #1427146) | Cod sursa (job #643309)
Cod sursa(job #643309)
#include <cstdio>
struct vecin
{
int nod,cost;
vecin* adr_urm;
};
vecin *vec[50001];
struct elc
{
int nod;
elc* adr_urm,*adr_prev;
};
elc *start,*end;
unsigned short int numapp[50001],eincoada[50001];
void vpush(int x,int y,int c)
{
vecin* tmp=new vecin;
tmp->nod=y;
tmp->cost=c;
tmp->adr_urm=vec[x];
vec[x]=tmp;
}
void push(int n)
{
if(!start)
{
start=new elc;
end=start;
start->nod=n;
start->adr_urm=start->adr_prev=NULL;
}
else
{
elc* tmp=new elc;
tmp->nod=n;
tmp->adr_urm=start;
start->adr_prev=tmp;
start=tmp;
}
}
void pop()
{
if(end!=start)
{
elc *tmp=end->adr_prev;
delete end;
end=tmp;
}
else
{
delete end;
end=start=NULL;
}
}
int main()
{
int cost[50001],n,m,x,y,c,nod;
bool cicneg=false;
start=end=NULL;
for(int i=0;i<=50000;i++)
{
cost[i]=2100000000;
eincoada[i]=numapp[i]=0;
vec[i]=NULL;
}
FILE *f=fopen("dijkstra.in","r");
fscanf(f,"%d %d\n",&n,&m);
for(int i=0;i<=m;i++)
{
fscanf(f,"%d %d %d",&x,&y,&c);
vpush(x,y,c);
}
fclose(f);
cost[1]=0;
push(1);
while(end&&!cicneg)
{
nod=end->nod;
pop();
eincoada[nod]=0;
for(vecin* curs=vec[nod];curs;curs=curs->adr_urm)
if(cost[nod]+curs->cost<cost[curs->nod])
{
cost[curs->nod]=cost[nod]+curs->cost;
if(!eincoada[curs->nod])
{
if(numapp[curs->nod]==n)
cicneg=true;
else
{
push(curs->nod);
eincoada[curs->nod]=1;
numapp[curs->nod]++;
}
}
}
}
f=fopen("dijkstra.out","w");
for(int i=2;i<=n;i++)
if(cost[i]<2100000000;
fprintf(f,"%d ",cost[i]);
else
fprintf(f,"0 ");
return 0;
}