Pagini recente » Cod sursa (job #1190616) | Cod sursa (job #50877) | Cod sursa (job #2111094) | Cod sursa (job #1251643) | Cod sursa (job #2172416)
#include <fstream>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
#define nmax 50003
#define inf 2000000000
struct nod
{
int val,cost;
nod *urm;
};
typedef nod *pnod;
pnod p,v[nmax];
int dist[nmax],heap[nmax],where[nmax];
int n,m;
void ad(int x,int y,int c)
{
p=new nod;
p->val=y;
p->cost=c;
p->urm=v[x]->urm;
v[x]->urm=p;
}
void upheap(int poz)
{
while(poz>1 and dist[heap[poz/2]]>dist[heap[poz]])
{
swap(heap[poz/2],heap[poz]);
swap(where[poz/2],where[poz]);
poz/=2;
}
}
int cate;
void downheap(int poz)
{
int new_pos;
do
{
new_pos=0;
if(poz*2<=cate)
{
new_pos=poz*2;
if(poz*2+1<=cate and dist[heap[2*poz+1]]<dist[heap[2*poz]])
new_pos+=1;
if(dist[heap[poz]]>dist[heap[new_pos]])
{
swap(heap[poz],heap[new_pos]);
swap(where[poz],where[new_pos]);
poz=new_pos;
}
else
new_pos=0;
}
}while(new_pos);
}
int main()
{
int i,x,y,c,now;
f>>n>>m;
for(i=1;i<=n;i++)
{
v[i]=new nod;
v[i]->urm=0;
dist[i]=inf;
where[i]=-1;
}
for(i=1;i<=m;i++)
{
f>>x>>y>>c;
ad(x,y,c);
}
dist[1]=0;
heap[1]=where[1]=1;
cate=1;
while(cate)
{
now=heap[1];
p=v[heap[1]]->urm;
where[heap[cate]]=1;
heap[1]=heap[cate];
downheap(1);
cate-=1;
while(p)
{
if(dist[p->val]>dist[now]+p->cost)
{
dist[p->val]=dist[now]+p->cost;
if(where[p->val]==-1)
{
cate+=1;
heap[cate]=p->val;
upheap(cate);
}
else
upheap(where[p->val]);
}
p=p->urm;
}
}
for(i=2;i<=n;i++)
if(dist[i]==inf)
g<<"0 ";
else
g<<dist[i]<<" ";
return 0;
}