Bellman-Ford & spfa Algorithm

Source: Internet
Author: User

Miyu original, post Please note: Reprinted from __________ White House

 


B-F

Applicability

    1. Single-source shortest path (from the source point S to all other vertices V );
    2. Directed Graph & undirected graph (undirected graphs can be seen as Directed Graphs (u, v) and (V, u) that belong to edge set E );
    3. Edge weight can be positive or negative (if an error message is displayed for negative weight loop output );
    4. Differential constraint system;


AlgorithmDescription

    1. perform | v |-1 relax (relaxation operation) operation on each edge.
    2. If (u, v) and E exist, the DIS [u] + W
For I: = 1 to | v |-1 do // V is the number of vertices for each side (u, v) ε E do // traverse each side relax (U, V, W); For each side (u, v) ε E do if dis [u] + W <dis [v] Then exit (false)


Time-Space complexity

Algorithm time complexity O (VE ). Because the algorithm is simple and widely applied, although the complexity is slightly higher, it is still a very practical algorithm.

 

Algorithm Improvement ---> spfa

 

Algorithm Overview

Spfa (Shortest Path Faster Algorithm) is a queue implementation of the Bellman-Ford algorithm, reducing unnecessary redundant computing. Some people also say that spfa was originally the Bellman-Ford algorithm, and the popular Bellman-Ford algorithm is actually a cottage version.


Algorithm flow

The general process of an algorithm is to use a queue for maintenance. Initially, the source is added to the queue. Each time an element is extracted from the queue and all neighboring points are relaxed. If a neighboring point is relaxed successfully, it is added to the queue. The algorithm ends when the queue is empty.

This algorithm, simply put, is the Bellman-Ford of queue optimization, which was invented using the features that each vertex does not update too many times.

Spfa -- Shortest Path faster algorithm, which can find the shortest path from the source point to all other points in the time complexity of O (KE) and process the negative edge. The implementation of spfa is even simpler than Dijkstra or bellman_ford:

Set DIST to represent the current shortest distance from S to I, and FA to represent the number of a vertex before I in the current shortest path from S to I. At the beginning, DIST is all + ∞, only Dist [s] = 0, and FA is all 0.

Maintain a queue that stores all vertices that need to be iterated. Initially, the queue only has one vertex S. Use a Boolean array to record whether each vertex is in a queue.

In each iteration, retrieve the vertex v in the head of the team, enumerate the edges V-> U starting from V in sequence, and set the edge length to Len, determine whether Dist [v] + Len is smaller than Dist [u]. If it is smaller than Dist [u], improve Dist [u] and Mark Fa [u] AS v, and because the shortest distance from S to u decreases, it is possible that u can improve other points. If U is not in the queue, put it at the end of the team. In this way, the iteration continues until the queue becomes empty, that is, the shortest distance from S to all is determined to end the algorithm. If a node has more than N queues, a negative weight ring exists.

The form of spfa is very similar to the width-first search. The difference is that the queue cannot be re-entered when a vertex in the width-first search, however, a point in spfa may be put into the queue again after the queue is out, that is, after a point is improved by another point, it may be improved after a period of time, so it is used again to improve other points, so that iteration continues. Set a vertex to improve other vertices by K on average. It can be proved that K is about 2 in common cases.


AlgorithmCode

 Procedure Spfa; Begin Initialize-single-source ( G, S ) ; Initialize-queue ( Q ) ; Enqueue ( Q, S ) ; While   Not Empty ( Q)   Do       Begin U: = dequeue ( Q ) ; For Each v adj [ U ]   Do           Begin TMP: = d [ V ] ; Relax ( U, V ) ;If   ( TMP <> d [ V ]  )   And   (  Not V In Q )   Then Enqueue ( Q, V ) ; End ; End ;End ;

 Procedure Spfa; Begin Fillchar ( Q, sizeof ( Q ) , 0  ) ; H: = 0 ; T: = 0 ; // Queue Fillchar( V, sizeof ( V ) , False  ) ; // V [I] determines whether I is in the queue    For I: = 1   To N Do Dist [ I ] : = Maxint; // Initialize the minimum value INC( T ) ; Q [ T ] : = 1 ; V [  1  ] : = True ; Dist [  1  ] : = 0 ; // Here 1 is used as the source point  While H <> T Do      Begin H: = ( H MoD N )  + 1 ; X: = Q [ H ] ; V [ X ] : = False ; For I: =1   To N Do          If   ( Cost [ X, I ] > 0  )   And   ( Dist [ X ] + Cost [ X, I ] <Dist [ I ]  )   Then            Begin Dist [ I ] : = DIST [ X ] + Cost [ X, I ] ; If   Not  ( V [ I]  )   Then                Begin T: = ( T MoD N )  + 1 ; Q [ T ] : = I; V [ I ] : = True ; End ; End ; End ; End ;
 Void Spfa (  Void  )  // I wrote it a long time ago ...... Lost today ...... I don't even remember how spfa was written ...... ...... The MS save graph is a matrix ...... Hmm  {   Int I; queue list; List. Insert  ( S ) ; For ( I = 1 ; I <= N; I ++ )    {     If  ( S = I )      Continue ; Dist [ I ] = Map [ S ]  [ I ] ; Way [ I] = S; If  ( Dist [ I ]  ) List. Insert  ( I ) ; }   Int P; While  ( ! List. Empty  ( )  )   { P = List. Fire  (  ) ; For  ( I = 1 ; I <= N; I ++ )     If  ( Map [ P ]  [ I ] && ( Dist [ I ] > Dist [ P ] + Map [ P ]  [ I ] |! Dist [ I ]  ) & I! = S )      { Dist[ I ] = DIST [ P ] + Map [ P ]  [ I ] ; Way [ I ] = P; If  ( ! List. In  ( I ) ) List. Insert  ( I ) ; }   }  }  

 

 

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.