Blue Bridge Cup-Shortest path (SPFA algorithm learning)

Source: Internet
Author: User

SPFA algorithm is mainly used to solve the existence of negative edge of the single source shortest-circuit situation (but can not have negative ring!!! A simple way to determine if there is no negative ring can be determined by whether a node is frequently in and out of the queue.

The following goes from 70045815

The full name of the SPFA algorithm for finding the shortest single source is: Shortest Path Faster algorithm.
The SPFA algorithm was published in 1994 by Southwest Jiaotong University Gefandine.
From the name we can see that this algorithm in terms of efficiency must have an extraordinary place.
Many times, given the graph exists negative right side, then like Dijkstra and other algorithms will not be used, and the complexity of Bellman-ford algorithm is too high, SPFA algorithm will come in handy. Some people call the SPFA algorithm the shortest-path universal algorithm.

For brevity, we agreed to a weighted graph G does not exist negative power loop, that is, the shortest path must exist. Of course, we can do a topological sort before executing the algorithm to determine if there is a negative power loop.
We use the array dis to record the shortest path estimate for each node, we can use adjacency matrix or adjacency table to store graph G, we recommend using adjacency table.

SPFA algorithm Idea (Dynamic approximation method):
 set up a FIFO queue q to hold the nodes to be optimized, optimize each time you remove the first node of the team, and use the current shortest path estimate of the U point to the node V pointed to the left U point slack operation, if the shortest path estimate of the V point is adjusted and the V point is not in the current queue, the V point is placed in the tail of the team. This keeps the nodes out of the queue for relaxation operations until the queue is empty.
The principle of relaxation operation is the famous theorem: "The sum of the two sides of the triangle is greater than the third side", in the informatics we call it triangular inequalities. The so-called node i,j relaxation, is to determine whether DIS[J]>DIS[I]+W[I,J], if the formula is set to DIS[J] reduced to dis[i]+w[i,j], or not move.
Here is an example to illustrate how the Sffa algorithm is performed:


< BR style= "margin:0px; padding:0px ">
and wide search BFS difference:
     SPFA in the form and breadth (width) of the first search is very similar, the difference is that one point in the BFS out of the queue is not possible to re-enter the queue, but a point in the SPFA may be placed in the queue again after the queue, That is, after a bit of improvement over the other points, after a while it may be improved (

Description of the algorithm:

voidSPFA (s);//finding the shortest distance from a single source point s to other vertices     forI=1to n Do{dis[i]=∞; vis[i]=false; }//the distance from each point to S is initialized, not the queuedis[s]=0;//set dis[source Point] to 0vis[s]=true;//source point s into the queueHead=0; Tail=1; Q[tail]=s;//The source point S is enqueued, and the tail pointer assigns initial value     whileHead<tail Do{Head+1;//team first Out teamV=q[head];//Team first Node vvis[v]=false;//release the Mark to V and you can re-queue        forEach side (V,i)//for each edge connected to the first V of the team        if(Dis[i]>dis[v]+a[v][i])//If the Triangle property is not satisfiedDis[i] = Dis[v] + a[v][i]//Relaxation Dis[i]        if(vis[i]=false) {tail+1; Q[tail]=i; vis[i]=true;}//is not queued, join queue}

How does the shortest path itself output?
in a diagram, we only know the shortest path length of Node A to node E, sometimes with little meaning. If this figure is a map model, after calculating the shortest path length, we always have to explain "how to go" to really solve the problem. How to record the shortest path in the process of calculation, and at the end of the output it?
We define a path[] array, path[i] denotes the shortest distance from the source point S to I, the number of nodes before the node I (parent node), we mark the Path[v]=u with the node v Slack, and the recorded work is done.
How to output it? What we're recording is what the point is at the front of each point, and the output is going to be output from the front to the back, which is good, recursive.

Template title:

Blue Bridge Cup-algorithm training shortest circuit

Idea: The SPFA algorithm, because the topic tells the existence negative side, does not exist the negative ring, but the node number n is large, therefore cannot use the Dijkstra algorithm and the Floyd algorithm.

Because the array cannot be opened too large, the adjacency table uses vectors to store a struct variable.

1#include <iostream>2#include <string.h>3#include <string>4#include <algorithm>5#include <bits/stdc++.h>6 #defineINF 1e97 using namespacestd;8 structnode{9     intnum;Ten     intLoad=INF; One }; AVector < Node > v[20000+ -]; - //int load[20050][20050]; - intlen[20050]; the BOOLvis[20050]; - voidSPFA () { -Queue <int>Q; -Q.push (1); +memset (Vis,0,sizeof(Vis)); -vis[1]=1; +      while(!Q.empty ()) { A         intnow=Q.front (); at Q.pop (); -vis[now]=0; -          for(intI=0; I<v[now].size (); i++){ -             inttmp=V[now][i].num; -             intlink=V[now][i].load; -             if(len[tmp]>link+Len[now]) { inlen[tmp]=link+Len[now]; -                 if(vis[tmp]==0){ to Q.push (TMP); +vis[tmp]=1; -                 } the             } *         } $     }Panax Notoginseng     return ; - } the intMain () { +      for(intI=0;i<20030; i++){ Alen[i]=INF; the     } +len[1]=0; -     intn,m; $Cin>>n>>m; $      for(intI=0; i<m;i++){ -         intx,y,l; - Node tmp; thescanf"%d%d%d",&x,&y,&l); -tmp.num=y;WuyiTmp.load=l; the V[x].push_back (TMP); -  Wu     } - SPFA (); About      for(intI=2; i<=n;i++){ $cout<<len[i]<<Endl; -     } -     return 0; -}

Blue Bridge Cup-Shortest path (SPFA algorithm learning)

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.