SPFA
求单源最短路的SPFA算法的全称是:Shortest Path Faster Algorithm
从名字我们就可以看出,这种算法在效率上一定有过人之处。很多时候,给定的图存在负权边,这时类似Dijkstra等算法便没有了用武之地,而Bellman-Ford算法的复杂度又过高,SPFA算法便派上用场了。
【伪代码】
伪代码 : function Dijkstra(Graph, source): dist[source] ← 0 // Distance from source to source for each vertex v in Graph: // Initialization if v ≠ source: // Where v has not yet been removed from Q (unvisited dist[v] ← infinity // Unknown distance function from source to v end if add v to Q // All nodes initially in Q (unvisited nodes) end for while Q is not empty: u ← vertex in Q with min dist[u] // Source node in first case remove u from Q for each neighbor v of u: // where v is still in Q. alt ← dist[u] + length(u, v) //松弛操作 if alt < dist[v]: // A shorter path to v has been found dist[v] ← alt; end if end for end while return dist[]
如果一个结点被加入队列超过n-1次,那么显然图中有负环。
这里给出一个简单的例题 HDU2544
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
3 2
【题目代码】
//SPFA shortest path faster algorithm #include <cstdio> #include <vector> #include <queue> #define INF 0xfffffff using namespace std; struct node{ int v,len; node(int v=0,int len=0):v(v),len(len){} }; vector<node>G[110]; int minDist[110]; int inqueue[110]; int n,m; void init(){ for(int i=0;i<110;i++){ minDist[i]=INF; inqueue[i]=0; G[i].clear(); } } int Kijkstra(){ inqueue[1]=true; queue<int >Q; minDist[1]=0; Q.push(1); while(!Q.empty()){ int vex = Q.front(); Q.pop(); inqueue[vex]=0; for(int i=0;i<G[vex].size();i++){ int v = G[vex][i].v; if(G[vex][i].len+minDist[vex]<minDist[v]){ minDist[v]=G[vex][i].len+minDist[vex]; if(!inqueue[v]) { inqueue[v]=1; Q.push(v); } } } } return minDist[n]; } int main(){ while(scanf("%d%d",&n,&m)!=EOF&&(n||m)){ init(); int a,b,len; for(int i=0;i<m;i++){ scanf("%d%d%d",&a,&b,&len); G[a].push_back(node(b,len)); G[b].push_back(node(a,len)); } int ans=Kijkstra(); printf("%d\n",ans); } return 0; }