Bellman-ford algorithm and SPFA algorithm to solve the shortest path template

Source: Internet
Author: User

The Bellman-ford algorithm is applicable to the shortest-path solution with negative weights , the complexity is O (VE), the principle is to each side of the relaxation operation, repeat the operation E-1 times after the shortest, if you can continue to relax, there is a negative ring. This is because the longest road without loops is just a V-point E-1, so the slack e-1 times must be the shortest. So this algorithm compared to Dijkstra first it is to the edge of the augmented, and then it can detect the existence of negative ring (if the negative ring exists, then the shortest path is not taken, because you can always around this negative ring will be the smallest paths constantly narrowing), this makes up for the Dijkstra of the shortcomings, but its algorithm runs relatively slow, So in order to pursue speed tends to use its "queue-optimized version" ==>SPFA, so want to understand SPFA better first look at Bellman-ford algorithm.

The SPFA algorithm is suitable for solving the shortest path with negative weights , the complexity of which is not so gadget in the ideal case, the paper points out that its complexity is O (KE) and K is a constant of about less than 2, but in some dense graphs, the algorithm performance will be degraded to Bellman-ford like O (VE), so in the dense map is recommended to use DIJ + Heap optimized version, sparse map SPFA is still very force! Found in the Bellman-ford, the outermost N-1 cycle is a bit blind, actually relaxed point we want it to continue to relax other points, so that we use the queue will be relaxed points to continue to relax the other points, the specific principles and practices can refer to the following links, by the way, SPFA also has two optimization ==> SLF and LLL, specifically not elaborated. This article mainly gives the template!

algorithm principle or learning reference links: dot me, dot me, Dot!

Bellman-ford templates

///example of POJ 2387#include <bits/stdc++.h>using namespacestd;Const intMAXN = 1e3 +Ten;Const intINF =0x3f3f3f3f;structedgenode{int  from, to, W;}; Edgenode EDGE[MAXN*MAXN];intDIS[MAXN];intN, M, Cnt;inlinevoidinit () { for(intI=0; i<=n; i++) Dis[i]=INF; CNT=0;}BOOLBellmanford (intSt) {Dis[st]=0;  for(intI=0; i<n; i++) {///N-1 cycles will definitely find the shortest path .        BOOLChanged =false; intTo, from, weight;  for(intj=0; j<cnt; J + +) { to=edge[j].to, from= Edge[j]. from, Weight=EDGE[J].W; if(dis[ from]!=inf && Dis[to] > dis[ from] +weight) {Changed=true; Dis[to]= dis[ from] +weight; ///Pre[to] = j;//record Paths            }        }        if(! Changed)return true;///If no side can continue to relax, it means that the algorithm ends without negative loops        if(I==n && Changed)return false;///have negative ring    }    return false;///in general, it's impossible to do this .}intMainvoid){     while(~SCANF ("%d%d", &m, &N))        {init (); int  from, to, weight;  for(intI=0; i<m; i++) {scanf (" %d%d%d", & from, &to, &weight); EDGE[CNT]. from= from; Edge[cnt].to=to ; EDGE[CNT].W=weight; CNT++; Edge[cnt].to= from; EDGE[CNT]. from=to ; EDGE[CNT].W=weight; CNT++; } Bellmanford (1); printf ("%d\n", Dis[n]); }    return 0;}
View Code

SPFA Template (SLF optimized version)

///example of POJ 2387#include <iostream>#include<cstdio>#include<cmath>#include<queue>#include<string.h>using namespacestd;Const intinf=0x3f3f3f3f;Const intMAXN = 1e3 +Ten;structedgenode{intV, W, NXT;}; Edgenode EDGE[MAXN*MAXN];BOOLVIS[MAXN];intHEAD[MAXN], DIS[MAXN], CNT;intN, M;///int PUSHCNT[MAXN];///record the number of each node in the queue, convenient to judge the negative ringinlinevoidinit () { for(intI=0; i<=n; i++)        ///Pushcnt[i] = 0;Head[i] =-1, Dis[i]=INF, Vis[i]=false; CNT=0;} InlinevoidAddedge (int  from,intTo,intweight) {EDGE[CNT].W=weight; EDGE[CNT].V=to ; EDGE[CNT].NXT= head[ from]; head[ from] = cnt++;}voidSPFA (intSt///to determine the negative ring, change to bool{deque<int>que;    Que.push_back (ST); VIS[ST]=true; DIS[ST]=0;  while(!Que.empty ()) {        intt=Que.front (); Que.pop_front (); Vis[t]=false;  for(intI=HEAD[T]; i!=-1; I=edge[i].nxt) {            intv=edge[i].v; intw=EDGE[I].W; if(dis[v]>dis[t]+W) {Dis[v]=dis[t]+W; ///P[v] = T;                if(!Vis[v]) {                    ///if (++pushcnt[v] > N) return false;//negative Ringvis[v]=true; if(!que.empty () && Dis[v] <Dis[que.front ()]) Que.push_front (v); ElseQue.push_back (v); //Que.push_back (v);///No SLF optimization It's written like this.                }            }        }    }    ///return true;}intMainvoid){     while(~SCANF ("%d%d", &m, &N))        {init (); int  from, to, weight;  for(intI=0; i<m; i++) {scanf (" %d%d%d", & from, &to, &weight); Addedge ( from, to, weight); Addedge (To, from, weight); } SPFA (1); printf ("%d\n", Dis[n]); }    return 0;}
View Code

Bellman-ford algorithm and SPFA algorithm to solve the shortest path template

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.