Pagini recente » Cod sursa (job #2482177) | Cod sursa (job #1316118) | Cod sursa (job #3200365) | Cod sursa (job #875464) | Cod sursa (job #2118125)
#include <fstream>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
#define nmax 50010
#define inf 2000000000
struct nod
{
int val,cost;
nod *urm;
};
typedef nod *pnod;
pnod p,v[nmax];
int dist[nmax],heap[nmax],poz[nmax],cate,minim;
bool use[nmax];
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 x)
{
while(x>1 and dist[heap[x]]<dist[heap[x/2]])
{
swap(heap[x],heap[x/2]);
swap(poz[heap[x]],poz[heap[x/2]]);
x/=2;
}
}
int ind;
void downheap(int x)
{
ind=1;
do
{
ind=0;
if(x*2<=cate)
{
ind=x*2;
if(ind+1<=cate and dist[heap[ind+1]]<dist[heap[ind]])
ind+=1;
if(dist[heap[x]]>dist[heap[ind]])
{
swap(heap[x],heap[ind]);
swap(poz[heap[x]],poz[heap[ind]]);
x=ind;
}
else
ind=0;
}
}while(ind);
}
int main()
{
int n,m,i,x,y,c;
f>>n>>m;
for(i=1;i<=n;i++)
{
v[i]=new nod;
v[i]->urm=0;
dist[i]=inf;
poz[i]=-1;
}
for(i=1;i<=m;i++)
{
f>>x>>y>>c;
ad(x,y,c);
}
heap[1]=1;
dist[1]=0;
poz[1]=1;
cate=1;
while(cate)
{
minim=heap[1];
swap(heap[1],heap[cate]);
poz[heap[1]]=1;
cate-=1;
downheap(1);
p=v[minim]->urm;
while(p)
{
if(dist[minim]+p->cost<dist[p->val])
{
dist[p->val]=dist[minim]+p->cost;
if(poz[p->val]==-1)
{
cate+=1;
heap[cate]=p->val;
poz[p->val]=cate;
upheap(cate);
}
else
upheap(poz[p->val]);
}
p=p->urm;
}
}
for(i=2;i<=n;i++)
if(dist[i]!=inf)
g<<dist[i]<<" ";
else
g<<"0 ";
return 0;
}