Graph Algorithm single-source shortest path Dijkstra algorithm (adjacent table/adjacent matrix + priority queue STL)

Source: Internet
Author: User

Graph Algorithm single-source shortest path Dijkstra algorithm (adjacent table/adjacent matrix + priority queue STL)

I. Preface

The shortest path algorithm, as its name implies, is used to solve the shortest distance, consumption, and cost between a certain point and a certain point. There are various descriptions on the map, it can be said that it is the shortest distance from one location to another. For example, if we think of every city on the map as a point, the cost from one city to another is different. Now we want to go from Shanghai to Beijing. We need to consider finding a route to minimize the cost from Shanghai to Beijing. Some people may first think that direct flights are, of course, the smallest method of time consumption, but considering the high cost, this line is not even as desirable as high-speed trains from Shanghai to Beijing. What's more, it takes a long time for the country to activate a route from Shanghai to Tibet, and then from Tibet to Lanzhou and other cities to reach Beijing after twists and turns, however, the price is very affordable compared with the previous two (assuming that only one dollar can be used to run more than half of China and enjoy the advantages of multiple provinces). From the perspective of saving money alone, it is naturally desirable to end with this article. This is what we call the single-source shortest path here. In the next section, we will explain the single-source shortest path of a directed graph with non-negative edge weights. As an undirected graph is equivalent to a disguised directed graph, we will not explain it here, and we will leave it for your own promotion.

Ii. Concepts

Here we will explain the shortest path and need to master several basic concepts:

For directed graph G = (V, E), the weight function W: E → R (that is, the weight of each edge is a real number)

1. Path

Iii. Optimal sub-structure

It is not difficult to find that solving the shortest path from a source point to a certain vertex is not as simple as solving the path from the source point to all vertices. In this case, we need to introduce the global concept. Can we find the shortest path of all vertices and then view the Shortest Path of the target point? Many people will think of the idea of Dynamic Planning and talk about dynamic planning. Naturally, the first question we need to consider is the optimal sub-structure.

The shortest path satisfies the optimal sub-structure: the sub-path of the shortest path is the shortest path.

Proof: (Cutting Method)

  

Premise: u to v is the shortest path.

Assume that x to y is not the shortest path, so there is a shorter path from x to y (assuming the following curved arrow). In this way, delete the path from x to y in the original path and replace it with the new path (bend arrow). Then a path shorter than the weight value from u to v is obtained, this is in conflict with the premise that u to v is the shortest path, so x to y is the shortest path, that is, the shortest path satisfies the optimal sub-structure nature.

Introduction of the Triangle Inequality concept: (the Shortest Path weight from u to v, less than or equal to the shortest path weight from u to x plus the Shortest Path weight from x to v)

    

This property is very important based on the optimal sub-structure.

Iv. Cell Shortest Path

For graph G = (V, E), specify the Source Vertex s and find the shortest path from s to all vertices v.

As we explain the Dijkstra algorithm in this article, we need to assume that there is no negative weight, that is:

    

Therefore, as long as the path exists, the shortest path exists.

V. Dijkstra algorithm ideas

Dijkstra is a very well-known computer scientist. Many people may understand him only in his cell shortest path algorithm. Those who know about the operating system may also understand his Banker algorithm, there are also goto harmful theories in the field of methodology. Of course, if we want to talk about other outstanding contributions, we have to move the topic far away. Today we will only talk about the thoughts of Dijkstra algorithm, and then give the implementation process in the future, it is necessary to give a proof of its correctness (Dijkstra invented the weakest predicate proof method in the field of Program correctness proof, but we will not use his method to prove the correctness of his old program, otherwise, it will be pulled to 108,000 -. -).

Algorithm idea:

(1) At any time, we must obtain the estimated distance from the source point to all vertices, and maintain a vertex set S. If vertex v is in S, the shortest path from the source point to the v is known;

(2) Each time a vertex v that is not in S is added to S, the Minimum Estimated distance from the source point to v is always selected;

(3) After vertex v is added to S, the estimated distance of all vertices adjacent to v (not S) is updated.

From (2), we see the greedy shadow. Every time we choose, we always want to choose the least cost. Normal people will think like this. As to why is this choice, we will prove it later.

The pseudocode is as follows:

1 Dijkstra (G, W, s) // G indicates the graph, W indicates the weight function, s indicates the Source Vertex 2 d [s] 1_0 // the shortest path from the Source Vertex to the Source Vertex is 0 3 for each v ε V-{s} // 3-8 rows are initialization operations 4 do d [v] limit ∞ 5 parent [v] limit NIL 6 S limit 7 Q limit V // here Q is the priority queue, stores vertices that have not entered S and the estimated distance from the source point to these vertices, which is implemented using a binary heap (minimum heap, the smaller the value, the higher the priority. 8 while Q =9 9 do u then Extract-Min (Q) // Extract the vertex with the Minimum Estimated distance, which is located at the top of the priority queue and goes out of the queue, place 10 S ← S limit {u} 11 for each v ε Adj (u) in the Set S. // perform the relaxation operation on each vertex v adjacent to the u, to maintain the establishment of the triangle inequality. 12 do if d [v]> d [u] + w (u, v) 13 then d [v] = d [u] + w (u, v) // This step implicitly updates the values in the priority queue. 14 parent [v] slave u // set the precursor node of v to u

Vi. Simple examples

Initial situation:

For the first relaxation, select Vertex:

 

For the second relaxation, the estimated distance of C is the smallest. Select the C vertex:

For the third relaxation, the estimated distance of E is the smallest. Select E:

For the fourth relaxation, the estimated distance of B is the smallest. Select B:

Fifth Relaxation: (the last point is complete)

After all the relaxation operations, we get the shortest path of all vertices (the red part in the table ).

If you add the parent [] operation, we can also get a shortest path tree, which readers can promote on their own.

VII. Code Implementation

Compared with the correctness, you may be more concerned with the implementation of the Code. Here we provide the Dijkstra implementation code. The graph structure is stored in two forms: the adjacent matrix and the adjacent table, for more information about the Graph Representation, see the following blog: http://www.cnblogs.com/dzkang2011/p/graph_1.html. Priority queue uses C ++ priority queue STL and priority_queue. Since the values in the queue cannot be directly changed, we need to slightly modify the implementation, which will not affect the final result, for details, see the code.

1. Adjacent Table C/C ++:

1 # include <iostream> 2 # include <cstdio> 3 # include <vector> 4 # include <queue> 5 using namespace std; 6 7 # define maxn 110 // maximum number of vertices 8 int n; // Number of vertices 9 10 struct arcnode // edge node 11 {12 int vertex; // vertex number 13 int weight adjacent to the header node; // weight of the edge connecting the two vertices 14 arcnode * next; // point to the next adjacent vertex 15 arcnode () {} 16 arcnode (int v, int w): vertex (v), weight (w), next (NULL) {}17}; 18 19 struct vernode // vertex node, 20 {21 int Vex; // The Current Fixed Point Number 22 arcnode * firarc; // edge formed by the first vertex connected to the vertex 23} Ver [maxn]; 24 25 void Init () // initialize the graph neighbor list and create the vertex node 26 {27 for (int I = 1; I <= n; I ++) 28 {29 Ver [I]. vex = I; 30 Ver [I]. firarc = NULL; 31} 32} 33 34 void Insert (int a, int B, int w) // end method, Insert With a as the start point, B as the end point, if the weight is w, the efficiency is not as good as that of the header insertion, but you can remove the duplicate edge 35 {36 arcnode * q = new arcnode (B, w); 37 if (Ver [a]. firarc = NULL) 38 Ver [a]. firarc = q; 39 else 40 {41 arcnode * P = Ver [a]. firarc; 42 if (p-> vertex = B) 43 {44 if (p-> weight> w) 45 p-> weight = w; 46 return; 47} 48 while (p-> next! = NULL) 49 {50 if (p-> next-> vertex = B) 51 {52 if (p-> next-> weight> w ); 53 p-> next-> weight = w; 54 return; 55} 56 p = p-> next; 57} 58 p-> next = q; 59} 60} 61 void Insert2 (int a, int B, int w) // the header insertion method is more efficient, but cannot remove the duplicate edge 62 {63 arcnode * q = new arcnode (B, w); 64 if (Ver [a]. firarc = NULL) 65 Ver [a]. firarc = q; 66 else 67 {68 arcnode * p = Ver [a]. firarc; 69 q-> next = p; 70 Ver [a]. firarc = q; 71} 72} 73 struct node // vertex node. Save the estimated distance between the id and the Source Vertex. The type of priority queue is 74 {75 int id; // Source Vertex id and estimated distance: 76 int w; 77 friend bool operator <(node a, node B) // sort the smallest heap in ascending order, therefore, you need to overload the operator and redefine the priority. The priority is 78 {79 return. w> B. w; 80} 81}; 82 83 # define INF 0 xfffff // The maximum weight is 84 int parent [maxn]; // Father's Day for each vertex, it can be used to restore the Shortest Path Tree 85 bool visited [maxn]; // It can be used to determine whether the vertex is already in the shortest path tree, or whether the Shortest Path 86 node d [maxn] has been found; // estimate the distance from the source vertex to each vertex. The final result is the shortest path from the Source Vertex to all vertices. 87 priority_queue <node> q; // The priority queue stl implements the 88 void Dijkstra (int s) // Dijkstra algorithm, which is passed to the Source Vertex 89 {90 for (int I = 1; I <= n; I ++) // initialize 91 {92 d [I]. id = I; 93 d [I]. w = INF; // set the estimated distance to INF 94 parent [I] =-1; // No Father's Day 95 visited [I] = false for each vertex; // none of them found the shortest 96} 97 d [s]. w = 0; // the shortest path from the source point to the source point is 0 98 q. push (d [s]); // press 99 while (! Q. empty () // the core of the algorithm. The queue empty description completes the operation 100 {101 node cd = q. top (); // obtain the minimum estimated distance from the vertex 102 q. pop (); 103 int u = cd. id; 104 if (visited [u]) // pay attention to the meaning of this sentence to avoid many unnecessary operations: 105 continue; 106 visited [u] = true; 107 arcnode * p = Ver [u]. firarc; 108 // relaxation operation 109 while (p! = NULL) // find all vertex adjacent to the vertex, perform the relaxation operation, update the estimated distance, and press it into the queue. 110 {111 int v = p-> vertex; 112 if (! Visited [v] & d [v]. w> d [u]. w + p-> weight) 113 {114 d [v]. w = d [u]. w + p-> weight; 115 parent [v] = u; 116 q. push (d [v]); 117} 118 p = p-> next; 119} 120} 121} 122 123 int main () 124 {125 int m, a, B, c, st, ed; 126 printf ("Enter the number of vertices and edges: \ n"); 127 scanf ("% d", & n, & m ); 128 printf ("Enter edge and weight (a, B, c) \ n"); 129 Init (); // before calculation, 130 while (m --) must be initialized --) 131 {132 scanf ("% d", & a, & B, & c); 133 Insert2 (a, B, c ); // undirected graph, pay attention to storing two sides: 134 Insert2 (B, a, c); 135} 136 printf ("Enter the start point and end point: \ n"); 137 scanf ("% d", & st, & ed); 138 Dijkstra (st); 139 if (d [ed]. w! = INF) 140 printf ("Shortest Path weight: % d \ n", d [ed]. w); 141 else142 printf ("the shortest path from vertex % d to vertex % d does not exist. \ N ", st, ed); 143 return 0; 144}

2. Adjacent matrix C/C ++:

1 # include <iostream> 2 # include <cstdio> 3 # include <queue> 4 using namespace std; 5 6 # define maxn 110 // maximum number of vertices 7 # define INF 0 xffffff // The maximum weight is 8 int w [maxn] [maxn]; // The adjacent matrix, storage weight 9 int n; // Number of vertices 10 11 struct node // vertex node, save the estimated distance between the id and the Source Vertex, the Type 12 {13 int id, weight required by the priority queue; // Source Vertex id and estimated distance 14 friend bool operator <(node a, node B) // to implement the smallest heap, sort it in ascending order. Therefore, you need to reload the operators and redefine the priority. The minimum heap is 15 {16 return. weight> B. weight; 17} 18}; 19 p Riority_queue <node> q; // priority queue, minimum heap, implements an important data structure of Dijkstra, and uses stl to implement 20 int parent [maxn]; // Father's Day for each vertex, it can be used to restore the Shortest Path Tree 21 bool visited [maxn]; // It can be used to determine whether the vertex is already in the shortest path tree, or whether the Shortest Path 22 node d [maxn] has been found; // estimate the distance from the source vertex to each vertex. The final result is the shortest path from the Source Vertex to all vertices. 23 void Dijkstra (int s) // Dijkstra algorithm, uploaded to the Source Vertex 24 {25 for (int I = 1; I <= n; I ++) // initialize 26 {27 d [I]. id = I; 28 d [I]. weight = INF; // The estimated distance is set to INF29 parent [I] =-1; // every vertex has no father's day point 30 visited [I] = false; 31} 32 d [s]. weight = 0; // the shortest path from the source to the source is 033 q. push (d [s]); // press 34 while (! Q. empty () // the core of the algorithm. The queue empty description completes the operation 35 {36 node cd = q. top (); // obtain the minimum estimated distance from vertex 37 q. pop (); 38 int u = cd. id; 39 if (visited [u]) 40 continue; 41 visited [u] = true; 42 // relaxation operation 43 for (int v = 1; v <= n; v ++) // find all the adjacent vertices, perform the relaxation operation, update the estimated distance, and press it into the queue. 44 {45 if (v! = U &&! Visited [v] & d [v]. weight> d [u]. weight + w [u] [v]) 46 {47 d [v]. weight = d [u]. weight + w [u] [v]; 48 parent [v] = u; 49 q. push (d [v]); 50} 51} 52} 53} 54 int main () 55 {56 int m, a, B, c, st, ed; 57 printf ("Enter the number of vertices and edges: \ n"); 58 scanf ("% d", & n, & m ); 59 printf ("Enter the edge and the weight (a, B, c) \ n"); 60 for (int I = 1; I <= n; I ++) // initialize 61 for (int j = I; j <= n; j ++) 62 w [I] [j] = w [j] [I] = INF; 63 while (m --) 64 {65 scanf ("% d", & A, & B, & c); 66 if (w [a] [B]> c) 67 w [a] [B] = w [B] [a] = c; 68} 69 printf ("Enter the start and end points: \ n "); 70 scanf ("% d", & st, & ed); 71 Dijkstra (st); 72 if (d [ed]. weight! = INF) 73 printf ("Shortest Path weight: % d \ n", d [ed]. weight); 74 else75 printf ("the shortest path from vertex % d to vertex % d does not exist. \ N ", st, ed); 76 return 0; 77}

 

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.