Graph Algorithm single-source shortest path Bellman_Ford algorithm (edge weight is negative), single-source bellman_ford

Source: Internet
Author: User

Graph Algorithm single-source shortest path Bellman_Ford algorithm (edge weight is negative), single-source bellman_ford

I. foresight

In the previous single-source shortest path Dijkstra algorithm, the blogger gave some basic concepts and Problems About shortest paths, the following figure shows how to use Dijkstra algorithm to solve the single-source shortest path problem.

We mentioned that a huge premise of Dijkstra algorithm is that it cannot have the edge with a negative value. When the weight value can be negative, there may be a negative weight loop in the figure. The shortest path only needs to go through this negative weight loop infinitely, the shortest path can be reduced without limit. This means that the shortest path does not exist and the Dijkstra algorithm cannot be terminated. It indicates that the shortest path from u to v does not exist.

Bellman_Ford algorithm. For issues related to the shortest path and the Dijkstra algorithm, refer to the following blog:

Http://www.cnblogs.com/dzkang2011/p/sp_dijkstra.html

Ii. Bellman_Ford algorithm ideas

If a negative weight loop exists in Figure G, some shortest paths do not exist.

The basic idea of the Bellman_Ford algorithm is to calculate the Shortest Path weight from the Source Vertex s to all other vertices. If a negative weight loop is encountered, a negative weight loop is reported and returned.

If there is no negative weight loop in the figure, the Bellman_Ford algorithm can obtain the result after a maximum of | V |-1 relaxation operation on all edges (google for proof ). After | V |-1 operation is completed, perform a relaxation test on all edges on the periphery. If the shortest path to some vertices can be reduced, note | V |-if the last result is not obtained after one relaxation, a negative weight loop must exist and return directly. If the number is no longer reduced, the shortest path has been found. For more information, see pseudocode comments.

The pseudocode is as follows:

Bellman_Ford (G, w, s) d [s] limit 0 // initialization, the shortest path from s to s is 0, others are positive infinity for each v ε V-{s} d [v] ∞
Parent [v] specify NIL // This function is used to generate the Shortest Path Tree.
For I want 1 to | V |-1 // experiment proves that only | V |-1 outer loop, | V | after-1 ends, if no negative weight loop exists in graph G, the shortest path from s to all other vertices is used to obtain the do for each edge (u, v) ε E // algorithm core, and each edge is relaxed, do if d [v]> d [u] + w (u, v) then d [v] ← d [u] + w (u, v)
Parent [v] ← u
For each edge (u, v) ε E // | V |-after one loop operation, if one side can be relaxed, it indicates that the shortest path to a certain point has not been found, so there must be a negative weight loop, and FALSE do if d [v]> d [u] + w (u, v) is returned) then return FALSE return TRUE // If no result is returned after the above relaxation, it means that all the D values will not be changed, then the Shortest Path weights are found completely, and TRUE is returned.

Iii. Simple examples

The following is a simple example to simulate the Bellman_Ford algorithm, because in the | V |-1 loop, we need to try to relax each edge. For convenience, we numbered each edge and relaxed it by number. In this way, the computer implementation is more convenient and will not affect the results.

Initial situation:

In the first round, the sides 4 and 5 can be relaxed in order to update vertices B and C:

In the second round, the edges 1, 3, 7, and 8 can be relaxed in order to update vertex E, D, C, and D:

In the third round, after a round, no changes are found and the cycle jumps out.

Note: if there is a negative weight loop, then | V |-1 must be completed, because each time it can be updated, minus the value of this negative weight loop.

Iv. Code Implementation

The following describes the C/C ++ implementation of the Bellman_Ford algorithm. Some optimizations can be made.

We found that during the | V |-1 loop operation, each update is related to the vertex's d value. If all the d values do not change, this will not affect the next result, so we can jump out of the loop in advance to avoid the following unnecessary operations.

  Implementation:

1 # include <iostream> 2 # include <cstdio> 3 using namespace std; 4 5 # define INF 0 xffff // maximum weight 6 # define maxe 5000 // maximum number of edges 7 # define maxn 100 // maximum number of vertices 8 int n, m; // Number of vertices and edges 9 int d [maxn]; // an array containing the Shortest Path weight 10 int parent [maxn]; // The precursor vertex of each vertex, used to restore the Shortest Path Tree 11 struct edge // represents the structure of the edge, because each edge needs to be relaxed by 12 {13 int u, v, w; // u as the edge starting point, v is the edge endpoint, w is the edge weight, can be negative 14} EG [maxe]; 15 16 bool Bellman_Ford (int s) // calculate the 17 {18 for (int I = 1; I <= N; I ++) // initialization operation d [EG [j]. v]> d [EG [j]. u] + EG [j]. w19 {20 d [I] = INF; 21 parent [I] =-1; 22} 23 d [s] = 0; 24 bool flag; // tag, judge whether the D value is updated. The reason for jumping out of the outer loop is 25 for (int I = 1; I <n; I ++) // The outer loop can be up to 26 {27 flag = false; // The initial value is false. If 28 for (int j = 0; j <m; j ++) // loosen m edges. if any, the flag is recorded as true29 if (d [EG [j]. v]> d [EG [j]. u] + EG [j]. w) // if d [v]> d [u] + w (u, v), update d [v] 30 {31 d [EG [j]. v] = d [EG [j]. u] + EG [j]. w; 32 parent [EG [J]. v] = EG [j]. u; 33 flag = true; 34} 35 if (! Flag) break; // if the flag status remains unchanged after each side is relaxed, no updates are found. You can directly jump out of the loop 36} 37 for (int I = 0; I <m; I ++) // After the above relaxation, if the relaxation still persists, it indicates that there is a negative weight loop and false38 if (d [EG [I] is returned. v]> d [EG [I]. u] + EG [I]. w) 39 return false; 40 return true; // returns true41} 42 43 int main () 44 {45 int st; 46 printf ("Enter n and m: \ n"); 47 scanf ("% d", & n, & m ); 48 printf ("Enter m edge (u, v, w): \ n"); 49 for (int I = 0; I <m; I ++) 50 scanf ("% d", & EG [I]. u, & EG [I]. v, & EG [I]. w); 51 print F ("Enter the start point:"); 52 scanf ("% d", & st); 53 if (Bellman_Ford (st )) 54 {55 printf ("no negative weight loop exists. \ N "); 56 printf (" the shortest path from the Source Vertex to each vertex is: \ n "); 57 for (int I = 1; I <= n; I ++) 58 printf ("% d", d [I]); 59 printf ("\ n"); 60} 61}

V. Test Results

In the above example, we conduct a test, where the vertices are converted into numbers:

Vi. Time Complexity Analysis

The implementation of the Bellman_Ford algorithm is much simpler than the Dijkstra algorithm using the priority queue, but the time complexity is not as good as that of the Dijkstra algorithm. From the code analysis, we can see that its complexity is O (VE ), V indicates the number of vertices, and E indicates the number of edges. However, at least now we can solve the negative weight.

(For more information, see the source .)


Why can the weight of the shortest path edge of a single source node of the bellman-ford algorithm be negative? Does the traversal cost have a negative value?

For example, if A is far away from home, he needs to select the best path from home to company to minimize the cost. In the company's case, there is a subsidy for the section of the bus, and the subsidy money is higher than the cost of the bus. At this time, when calculating the minimum cost, the weight of this edge should be defined as a negative value.
 
Similarities and differences between the dijakstra algorithm and the branch Limit algorithm in solving the single-source shortest path problem

Note that the dijakstra algorithm is a D algorithm.
The D algorithm is greedy, and each step is the best in the current step. The complexity is O (n * n) (also called climbing)
Branch restriction algorithm, where the diffusion of each step is the optimum degree of current dissipation and the complexity is (not calculated)

These are all extreme scenarios of algorithm.
(Wrong. The branch restriction algorithm in my text below is actually about the dynamic programming method. I checked the book and the dynamic programming method is an improvement to the branch restriction method, the branch limit method does not belong to algorithm A (heuristic search algorithm). However, dynamic planning and D algorithms are also comparable, it is also possible to directly use the branch Limit algorithm and the D algorithm)
Keywords: Dissipation Degree Evaluation Function
That is, the criteria for determining the current priority search direction are as follows: Possible Optimal Solution
The optimal solution can be done using an evaluation function, that is, the existing dissipation degree plus the possible consumption degree in the future.
Algorithm A adds two dissipation degrees together as the search direction of the current state;
However, it is difficult to evaluate the degree of dissipation in the future. The D algorithm regards the shortest of the current path as the basis for evaluating the degree of dissipation in the future.
The branch restriction algorithm is only used to evaluate the function based on the previous dissipation degree.

The two algorithms you give are of course the special case of algorithm.
You can also refer to the * algorithm modified by the * algorithm. I believe it will be helpful for your programming level.

Refer:
The method of searching and resolving the spatial tree by the queue-type branch limit method is similar to the width-first search of the solution spatial tree, the difference is that the queue-based branch restriction method does not search for Subtrees with the root node as a non-feasible node (the node that has been determined to cannot lead to a feasible solution or cannot lead to an optimal solution. According to the Rules, such nodes are not included in the dynamic node table.

The search method of the priority queue branch restriction method is to determine the next extension node based on the priority of the active node. The priority of a node is usually expressed by a value p related to the node. The maximum priority queue specifies a higher priority for knots with a larger P value. In Algorithm Implementation, a maximum heap is often used to implement the maximum priority queue, reflecting the principle of maximum benefit first. Similarly, nodes with a smaller P value specified by the minimum priority queue have a higher priority. A minimum heap is often used for Algorithm Implementation to reflect the principle of least priority. When a priority queue branch and demarcation algorithm is used to solve specific problems, the maximum or minimum priority queue should be selected based on the characteristics of the problem to determine the P values of each knot point.

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.