The Dijkstra (Dijkstra) Shortest path algorithm is a short-circuit algorithm that has been rigorously proven for time complexity.
Optimization is the use of heap optimization each time the minimum value, but in the shortest path relaxation process, dist is constantly modified, so, in order to be able to reduce the complexity to O (NLOGN), dist modification, in the heap also to be modified.
Note that the Dijkstra (Dijkstra) Shortest path algorithm can only be used for positive weight edges.
1#include <cstdio>2#include <cstring>3#include <iostream>4#include <algorithm>5 using namespacestd;6 7 Const intmaxn=10001;8 Const intmaxm=400002;9 intn,m;Ten intDIST[MAXN]; One A intLen; - intHEAD[MAXN],NEXT[MAXM],ADJ[MAXM],WEIGHT[MAXM]; - intC; the - intPOS[MAXN]; - - structnode + { - intDist,id; + }HEAP[MAXN]; A at voidPushdown (intx) - { - inti; - while((i=x<<1) <=len)//Len - { - if(i<len&&heap[i].dist>heap[i+1].dist) i++;//I<len in if(heap[i].dist<heap[x].dist) - { to swap (heap[i],heap[x]); +pos[heap[i].id]=i; -pos[heap[x].id]=x; thex=i; * } $ Else Break;Panax Notoginseng } - } the + voidbuild () A { the for(intI=1; i<=n;i++) + { -heap[i].dist=Dist[i]; $Heap[i].id=i; $pos[i]=i; - } - for(inti=n/2; i>=1; i--) the pushdown (i); - }Wuyi the voidAdjustintID) - { Wu intI=Pos[id]; -heap[i].dist=Dist[id]; About while(i>1&&heap[i].dist2].dist) $ { -Swap (heap[i],heap[i/2]); -I/=2; -pos[heap[i*2].id]=i*2; A } +pos[id]=i; the } - $ inttaketop () the { the inttop=heap[1].id; theheap[1]=heap[len--]; thePushdown (1); - returntop; in } the the voidAddedge (intUintVintW) About { theC++; theadj[c]=v; thenext[c]=Head[u]; +Weight[c]=w;// -head[u]=C; the }Bayi the voidDijkstraints) the { -memset (Dist,0x7f7f7f7f,sizeof(Dist)); -dist[s]=0; theBuild ();// the for(intA=1; a<=n;a++) the { the intp=taketop (); - for(intI=head[p];i;i=Next[i]) the { the intv=Adj[i]; the if(dist[v]>dist[p]+Weight[i])94 { thedist[v]=dist[p]+Weight[i]; the Adjust (v); the }98 } About } - 101 }102 103 intMain ()104 { theFreopen ("dijkstra.in","R", stdin);106Freopen ("Dijkstra.out","W", stdout);107scanf"%d%d",&n,&m);108 ints,e;109scanf"%d%d",&s,&e); thelen=N;111 for(intI=1; i<=m;i++) the {113 inta,b,w; thescanf" %d%d%d",&a,&b,&W); the Addedge (a,b,w); the Addedge (b,a,w);117 }118 Dijkstra (s);119 //for (int i=1;i<=n;i++) - //printf ("%d:%d\n", I,dist[i]);121printf"%d", Dist[e]);122 return 0;123}
View Code
Dijkstra (Dijkstra) Shortest path algorithm for heap optimization