Queue priority optimization for DJ algorithm

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.