"Algorithm" C + + code Dijkstra

Source: Internet
Author: User

Single source is the shortest circuit, the complexity is O (N²), and the heap is optimized O (NLOGN). The basic idea is greed, each time to join a current closest point, can prove each time the nearest point is the shortest path at the moment. Therefore, when all points are added, the shortest path from the starting point to all points is calculated.

In the implementation, it should be noted that in the heap of a point I, not as long as the shortest path length of the current to I D[i], but also remember that this is the length of the I point . In other words, be able to know at any time the corresponding value of point d[i] in the heap position, and a point in the heap h[k] corresponding to the point I. My approach is to use two arrays in the heap to maintain this one by one corresponding relationship.

Here's the pseudo-code for the subject:

1 d←∞, Heap h is empty2d[s]=03  for(A bit i) H.inch(I,d[i]);4  while(heap non-empty)5 {6U=h. out();7      for(All sides u->v)8         if(d[v]>d[u]+(u,v))9         {Tend[v]=d[u]+(u,v); One h.update (V,d[v]); A         } -}

Finally, the Dijkstra algorithm, not only can not appear to let the shortest path disappears negative right ring, also cannot appear negative right side. Because it is greedy, once the negative right side, then may go to a longer side, and then through the negative right side to come back, to achieve a shorter path, so Dijkstra greedy ideas will expire.

Heap optimization will not be written, there is time to add it.

"Algorithm" C + + code Dijkstra

Related Article

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.