DJ algorithm is to find the shortest-single source algorithm, but the time complexity is not ideal, so the minimum heap to optimize the algorithm.
If you do not know the priority queue, you can first see the STL classification about priority queue Introduction;
#include <stdio.h>#include<algorithm>#include<string.h>#include<queue>#defineMAX 21000#defineINF 0x3f3f3f3fusing namespacestd;structnod{intv; intNet;} eg[2*MAX];structnoo{intx; ints; BOOL operator< (ConstNoo & A)Const { returns<A.S; }}t,temp;inthead[max],cnt;BOOLBook[max];intD[max];voidBuildintFormintTo ) {EG[CNT].V=to; eg[cnt].net=head[form];head[form]=cnt++;}voidDjints) {Priority_queue<noo>Q; D[s]=0; T.x=s; T.S=0; Q.push (t); while(!Q.empty ()) {T=q.top (); Q.pop (); if(d[t.x]<T.s)Continue; for(inti=head[t.x];i!=-1; i=eg[i].net) { if(d[eg[i].v]>d[t.x]+1) {D[EG[I].V]=d[t.x]+1; Temp.x=eg[i].v; TEMP.S=D[EG[I].V]; Q.push (temp); } } }}intMain () {intn,m,u,v; while(SCANF ("%d%d", &n,&m)! =EOF) {memset (head,-1,sizeof(head)); memset (book,0,sizeof(book)); memset (D,inf,sizeof(d)); CNT=0; intst=0, en=0; for(intI=0; i<m; i++.) {scanf ("%d%d",&u,&v); Build (U,V); Build (V,u); } DJ (1); }}
View Code
The algorithm realizes the shortest distance from 1 to each point;
Queue priority optimization for DJ algorithm