[Template] dijkstra (heap optimization)

Complexity of O (mlogn)

Enter the starting point s, the shortest distance can be obtained from the starting point to the respective array dis point [i]

process:

1. Initialization: Empty tag array, the array initialization distance to inf, from the starting point to 0, open priority queue, search for the starting point

2. Search: Remove the head of the queue and pop, head of the queue if the current node is the shortest u u shortest path than the original large skip, or traverse the neighbors if u v and u have not been accessed in the shortest plus most short-circuit current is less than the original right adjacent Collage v, updating and searching the shortest v v

 1 void dijkstra(int s){
 2     memset(vis,0,sizeof vis);
 3     memset(dis,inf,sizeof dis);
 4     dis[s]=0;
 5     priority_queue<node> q;
 6     node a(s,dis[s]);
 7     q.push(a);
 8     while(q.size()){
 9         node x=q.top();q.pop();
10         int u=x.pos;
11         if(x.val>dis[u])continue;
12         for(int I = head [U]; ~ I; I = E [I] .nex) {
 13 is              int V = E [I] .to;
 14              IF (VIS [V] && (DIS [V]> E [I! ] .W + DIS [U])) {
 15                  DIS [V] = E [I] .W + DIS [U];
 16                  a.pos = V, = a.val DIS [V];
 . 17                  q.push (A) ;
 18              }
 19          }
 20      }
 21  }
 22  / * *
 23  initialization: empty tag array, from array to initialize INF, 0 is set to point distance, open priority queue, a search start point
 24  Search: remove the head of the queue and pop, if team the first node u the most shorted than the original shortest u large skip, or traversing the adjacent points u v,
 25  if not accessed v and u the shortest path plus the current weight is less than the adjacent Collage of original v the shortest, the shortest path is updated and the search v v
26 **/

 

Guess you like

Origin www.cnblogs.com/Railgun000/p/11407457.html