Pagini recente » Cod sursa (job #1807784) | Cod sursa (job #1933487) | Cod sursa (job #535490) | Cod sursa (job #977461) | Cod sursa (job #2240502)
#include <fstream>
#include <iostream>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int n,m;
struct laturi {int dest,cost;laturi *next;} *a[50002];
//dm=drum minim,h=inaltime,poz=pozitia in H,pz=pozitie max
//astfel,h[i]-nodul de pe poz i
//poz[h[i]]=i;
//dm[h[i]]=drumu minim al nodului de pe poz i
int pih[50002],h[50002],dm[50002],pz;
//x=plecare,y=destinatar,z=cost
void adauglat(int x,int y,int z)
{
laturi *nou=new laturi;
nou->cost=z;
nou->dest=y;
nou->next=a[x];
a[x]=nou;
}
void downem(int pzt)
{
if(pzt*2<=pz)
{
if(dm[h[pzt*2]]<dm[h[pzt]])if(pzt*2+1>pz||dm[h[pzt*2]]<dm[h[pzt*2+1]])
{
swap(h[pzt*2],h[pzt]);
swap(pih[h[pzt*2]],pih[h[pzt]]);
downem(pzt*2);
}
if(pzt*2+1<=pz)if(dm[h[pzt*2+1]]<dm[h[pzt]])
{
swap(h[pzt*2+1],h[pzt]);
swap(pih[h[pzt*2+1]],pih[h[pzt]]);
downem(pzt*2+1);
}
}
}
void upem(int pzt)
{
if(pzt!=1)if(dm[h[pzt/2]]>dm[h[pzt]])
{
swap(h[pzt/2],h[pzt]);
swap(pih[h[pzt/2]],pih[h[pzt]]);
upem(pzt/2);
}
}
void addneighbours(int q)
{
int c,d,numer=0;
while (a[q]!=NULL)
{
c=a[q]->cost;
d=a[q]->dest;
if(dm[d]>c)
{
if(dm[d]==20009){h[++pz]=d;pih[d]=pz;}
dm[d]=c+dm[q];
upem(pih[d]);
}
a[q]=a[q]->next;
if(a[q]==NULL)break;
++numer;
}
}
int main()
{
f>>n>>m;
for(int i=1;i<=m;++i)
{
int x,y,z;
f>>x>>y>>z;
adauglat(x,y,z);
adauglat(y,x,z);
}
for(int i=2;i<=n;++i){dm[i]=20009;pih[i]=-1;}
pz=1;
dm[1]=0;
pih[1]=1;
h[1]=1;
while(pz!=0)
{
addneighbours(h[1]);
swap(h[1],h[pz]);
--pz;
downem(1);
}
for(int i=2;i<=n;++i){if(dm[i]!=20009)g<<dm[i]<<" ";
else g<<"0 ";}
}