SPFA Bellman-Ford algorithm is a processing queue with high efficiency. But he is not stable.
. 1 #include <bits / STDC ++ H.> 2 the using namespace STD; . 3 . 4 const int INF = 0x3f3f3f3f ; . 5 const int NUM = ??? ; . 6 struct Edge { . 7 int from , to, W; // edge: starting from (actually not used), to the end point, weighting values (distance) W . 8 Edge ( int A, int B, int C) { from = A; B = to; W = C;} . 9 }; 10 Vector <Edge> E [NUM]; // node i is connected to all of the edges 11 int n-, m; 12 is int DIS [NUM]; // from the point i of the predetermined distance 13 is int pre [NUM]; // record the path 14 15 @ printing path 16 void print_path ( int S, int T) { . 17 IF (S == T) {the printf ( " % D " , S); return ;} 18 is print_path (S, pre [T]); . 19 the printf ( " -> D% " , T); 20 is } 21 is 22 is int SPFA ( int S) { 23 is BOOL INQ [NUM]; // tag node i is in the queue 24 int NEG [NUM]; // Analyzing negative ring 25 // initialization 26 is for ( int i = . 1 ; i <= n-; i ++ ) { 27 NEG [I] = 0 ; 28 DIS [I] = INF; 29 INQ [I] = to false ; 30 } 31 is NEG [S] = . 1 ; 32 // 33 is Queue < int > Q; 34 is q.push (S); 35 INQ [S] = to true ; // S into the team 36 // 37 [ the while (! {q.empty ()) 38 is int U = q.front (); 39 q.pop (); 40 INQ [U] = to false ; // S dequeue 41 is 42 is for ( int I = 0 ; I <E [u] .size (); I ++) { // all edges connected to the check node u 43 is int V = E [u] [I]. to, W = E [U] [I] .W; 44 is IF (DIS [U] + W <DIS [v]) { // starting point -> u-> v is from <origin - from> v. 45 DIS [v] = DIS [U] + W; 46 is pre [v] = U; 47 IF (! INQ [v]) { // If v is not inserted into the queue 48 INQ [v] = to true ; 49 q.push (v); 50 NEG [v] ++ ; 51 is IF (NEG [v]> n-) return . 1 ; // number of update v exceeds the number of nodes, then there is a negative ring 52 } 53 } 54 } 55 } 56 // print_path (S ,?); 57 is return 0; 58 } 59 60 int main(){ 61 while(~scanf("%d %d", &n, &m) && n && m){ 62 for(int i=1; i<=n; i++) e[i].clear(); 63 while(m--){ 64 int a, b, c; 65 scanf("%d %d %d", &a, &b, &c); 66 e[a].push_back(edge(a,b,c)); 67 e[b].push_back(edge(b,a,c)); 68 } 69 SPFA ( 1 ); // predetermined starting 1 70 } 71 is return 0 ; 72 }