Book--图论最短路 Spfa
2014-09-11 19:54:17
推荐下博客:http://www.cnblogs.com/scau20110726/archive/2012/11/18/2776124.html
算法简介:SPFA(Shortest Path Faster Algorithm)算法是求单源最短路径的一种算法,在Bellman-ford算法的基础上加上一个队列优化,减少了冗余的松弛操作,是一种高效的最短路算法。度娘给的,个人感觉SPFA更像是Dij的优化QAQ。这个算法的优点:速度快,能够处理负环。
常用思想:(1)有DFS版和BFS版的SPFA,DFS版判负环速度比BFS快。DFS写得短。BFS写着顺,容易改。
(2)建图能用数组表示链表就用。
(3)要注意考虑正向求最短路和反向最短路哪个更适合!
(4)注意考虑重边!
小贴个Spfa模板把,复习下数组实现链表。hdu 2544
1 /************************************************************************* 2 > File Name: 2544.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Thu 11 Sep 2014 07:02:11 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <vector> 13 #include <queue> 14 #include <iostream> 15 #include <algorithm> 16 using namespace std; 17 typedef long long ll; 18 const int INF = 1 << 29; 19 20 int N,M,ans; 21 int v[20005],w[20005]; 22 int first[105],next[20005]; 23 24 void Init(){ 25 memset(first,0,sizeof(first)); 26 } 27 28 void Spfa(int s){ 29 queue<int> q; while(!q.empty()) q.pop(); 30 int d[105],c[105],inq[105]; 31 memset(d,0x3f,sizeof(d)); 32 memset(inq,0,sizeof(inq)); 33 memset(c,0,sizeof(c)); 34 d[s] = 0; 35 inq[s] = c[s] = 1; 36 q.push(s); 37 while(!q.empty()){ 38 int x = q.front(); q.pop(); 39 inq[x] = 0; 40 for(int y = first[x]; y; y = next[y]) if(d[v[y]] > d[x] + w[y]){ 41 d[v[y]] = d[x] + w[y]; 42 if(!inq[v[y]]){ 43 inq[v[y]] = 1; 44 c[v[y]]++; 45 if(c[v[y]] > N) return; 46 q.push(v[y]); 47 } 48 } 49 } 50 printf("%d\n",d[N]); 51 } 52 53 int main(){ 54 int tu,tv,tw; 55 while(scanf("%d%d",&N,&M) != EOF && (N || M)){ 56 Init(); 57 M <<= 1; 58 for(int i = 1; i <= M; ++i){ 59 scanf("%d%d%d",&tu,&tv,&tw); 60 next[i] = first[tu]; 61 first[tu] = i; 62 v[i] = tv; 63 ++i; 64 next[i] = first[tv]; 65 first[tv] = i; 66 v[i] = tu; 67 w[i] = w[i - 1] = tw; 68 } 69 Spfa(1); 70 } 71 return 0; 72 } 73 74

浙公网安备 33010602011771号