最短路徑算法——Dijkstra,Bellman-Ford,Floyd-Warshall,Johnson,無一倖免

文章出自:http://dsqiu.iteye.com/blog/1689163

最短路徑算法——Dijkstra,Bellman-Ford,Floyd-Warshall,Johnson,無一倖免

本文內容框架:

§1 Dijkstra算法

§2 Bellman-Ford算法

§3 Floyd-Warshall算法

§4 Johnson算算法

§5 問題歸約

 

§6 小結

常用的最短路徑算法有:Dijkstra算法、Bellman-Ford算法、Floyd-Warshall算法、Johnson算法

最短路徑算法可以分爲單源點最短路徑和全源最短路徑。

單源點最短路徑有Dijkstra算法和Bellman-Ford算法,其中Dijkstra算法主要解決所有邊的權爲非負的單源點最短路徑,Bellman-Ford算法可以適用權值有負值的問題。

全源最短路徑主要有Floyd-Warshall算法和Johnson算法,其中Floyd算法可以檢測圖中的負環並可以解決不包括負環的圖中全源最短路徑問題,Johnson算法相比Floyd-Warshall算法,效率更高。

算法性能分析

在分別講解這四個算法之前先來理清下這個四個算法的複雜度:Dijkstra算法直接實現時間複雜度是O(n²),空間複雜度是O(n)(保存距離和路徑),二叉堆實現時間複雜度變成O((V+E)logV),Fibonacci Heap可以將複雜度降到O(E+VlogV);Bellman-Ford算法時間複雜度是O(V*E),SPFA是時間複雜度是O(kE);Floyd-Warshall算法時間複雜度是O(n³),空間複雜度是O(n²);Johnson算法時間複雜度是O( V * E * lgd(V) ),比Floyd-Warshall算法效率高。

 

最短路徑算法之Dijkstra算法

 

§1 Dijkstra算法

 

 

Dijkstra算法思想

Dijkstra算法思想爲:設G=(V,E)是一個帶權有向圖(無向可以轉化爲雙向有向),把圖中頂點集合V分成兩組,第一組爲已求出最短路徑的頂點集合(用S表示,初始時S中只有一個源點,以後每求得一條最短路徑 , 就將 加入到集合S中,直到全部頂點都加入到S中,算法就結束了),第二組爲其餘未確定最短路徑的頂點集合(用U表示),按最短路徑長度的遞增次序依次把第二組的頂點加入S中。在加入的過程中,總保持從源點v到S中各頂點的最短路徑長度不大於從源點v到U中任何頂點的最短路徑長度。此外,每個頂點對應一個距離,S中的頂點的距離就是從v到此頂點的最短路徑長度,U中的頂點的距離,是從v到此頂點只包括S中的頂點爲中間頂點的當前最短路徑長度。

 

Dijkstra算法具體步驟  

(1)初始時,S只包含源點,即S={v},v的距離dist[v]爲0。U包含除v外的其他頂點,U中頂點u距離dis[u]爲邊上的權值(若v與u有邊) )或∞(若u不是v的出邊鄰接點即沒有邊<v,u>)。

(2)從U中選取一個距離v(dist[k])最小的頂點k,把k,加入S中(該選定的距離就是v到k的最短路徑長度)。

(3)以k爲新考慮的中間點,修改U中各頂點的距離;若從源點v到頂點u(u∈ U)的距離(經過頂點k)比原來距離(不經過頂點k)短,則修改頂點u的距離值,修改後的距離值的頂點k的距離加上邊上的權(即如果dist[k]+w[k,u]<dist[u],那麼把dist[u]更新成更短的距離dist[k]+w[k,u])。

(4)重複步驟(2)和(3)直到所有頂點都包含在S中(要循環n-1次)。

╝①

 

Dijkstra算法實現

直接實現

最簡單的實現方法就是,在每次循環中,再用一個循環找距離最短的點,然後用任意的方法更新與其相鄰的邊,時間複雜度顯然爲O(n²)

對於空間複雜度:如果只要求出距離,只要n的附加空間保存距離就可以了(距離小於當前距離的是已訪問的節點,對於距離相等的情況可以比較編號或是特殊處理一下)。如果要求出路徑則需要另外V的空間保存前一個節點,總共需要2n的空間。

╝②

 

Cpp代碼  收藏代碼
  1. /********************************* 
  2. *   最短路徑---Dijkstra算法實現  
  3. *      HDU:2544  
  4. *   BLOG:www.cnblogs.com/newwy 
  5. *   AUTHOR:Wang Yong 
  6. **********************************/  
  7. #include <iostream>  
  8. #define MAX 100  
  9. #define INF 1000000000  
  10. using namespace std;  
  11.  int dijkstra (int mat[][MAX],int n, int s,int f)  
  12.  {  
  13.      int dis[MAX];  
  14.      int mark[MAX];//記錄被選中的結點   
  15.      int i,j,k = 0;  
  16.      for(i = 0 ; i < n ; i++)//初始化所有結點,每個結點都沒有被選中   
  17.          mark[i] = 0;  
  18.     for(i = 0 ; i < n ; i++)//將每個結點到start結點weight記錄爲當前distance   
  19.     {  
  20.         dis[i] = mat[s][i];  
  21.         //path[i] = s;  
  22.     }  
  23.     mark[s] = 1;//start結點被選中   
  24.     //path[s] = 0;  
  25.     dis[s] = 0;//將start結點的的距離設置爲0   
  26.     int min ;//設置最短的距離。   
  27.     for(i = 1 ; i < n; i++)  
  28.     {  
  29.         min = INF;  
  30.         for(j = 0 ; j < n;j++)  
  31.         {  
  32.             if(mark[j] == 0  && dis[j] < min)//未被選中的結點中,距離最短的被選中   
  33.             {  
  34.                 min = dis[j] ;  
  35.                 k = j;  
  36.             }  
  37.         }  
  38.         mark[k] = 1;//標記爲被選中   
  39.         for(j = 0 ; j < n ; j++)  
  40.         {  
  41.             if( mark[j] == 0  && (dis[j] > (dis[k] + mat[k][j])))//修改剩餘結點的最短距離   
  42.             {  
  43.                 dis[j] = dis[k] + mat[k][j];  
  44.             }  
  45.         }  
  46.     }  
  47.     return dis[f];      
  48.  }   
  49.  int mat[MAX][MAX];  
  50. int main()  
  51. {  
  52.     int n,m;  
  53.     while(scanf("%d %d",&n,&m))  
  54.     {  
  55.         int a,b,dis;  
  56.         if(n == 0 || m == 0)  
  57.             break;  
  58.         int i,j;  
  59.         for(i = 0 ; i < n;i++)  
  60.             for(j = 0 ; j < n; j++)  
  61.                 mat[i][j] = INF;  
  62.         for(i = 0 ; i < m ;i++)  
  63.         {  
  64.             scanf("%d %d %d",&a,&b,&dis);  
  65.             --a,--b;  
  66.             if(dis < mat[a][b] || dis < mat[b][a])  
  67.             mat[a][b] = mat[b][a] = dis;  
  68.         }  
  69.         int ans = dijkstra(mat,n,0,n-1);  
  70.         printf("%d\n",ans);  
  71.     }  
  72.    
  73. }  

 ╝⑤

二叉堆實現

使用二叉堆(Binary Heap)來保存沒有擴展過的點的距離並維護其最小值,並在訪問每條邊的時候更新,可以把時間複雜度變成O((V+E)logV)。

當邊數遠小於點數的平方時,這種算法相對來說有很好的效果。但是當E=O(V2)時(有時候表現爲不限制邊的條數),用二叉堆的優化反倒會更慢。因爲此時的複雜度是O(V+V*2logV),小於不用堆的實現的O(n²)的複雜度。

另外此時要用鄰接表保存邊,使得擴展邊的總複雜度爲O(E),否則複雜度不會減小。

空間複雜度:這種算法需要一個二叉堆,及其反向指針,另外還要保存距離,所以所用空間爲3V。如果保存路徑則爲4V。

具體思路:先將所有的點插入堆,並將值賦爲極大值(maxint/maxlongint),將原點賦值爲0,通過鬆弛技術(relax)進行更新以及設定爲擴展。

╝②

 

C代碼  收藏代碼
  1. int  GraphDijk(struct Graph *g, int root, int *parent, int *distance)  
  2. {  
  3.     // 將除根結點之外的點都放入堆中,設置所有鍵爲INFINITY  
  4.     // 遍歷根結點發出的邊,將其最短路徑設爲相應權值,並維持堆性質  
  5.     // RemoveTop,此結點已經取最短路徑,如果爲INFINITY,則終止算法  
  6.     // 否則,將其狀態設爲已標記,並設爲根結點  
  7.     // loop back  
  8.     parent[root] = root;  
  9.     int reflection[g->V];  
  10.     int heap_real[g->V - 1];  
  11.     for (int i=0,j=0; i < g->V; i++) {  
  12.         if (i == root) {  
  13.             distance[i] = 0;  
  14.         } else {  
  15.             distance[i] = INFINITY;  
  16.             heap_real[j++] = i;  
  17.             reflection[i] = j;  
  18.         }  
  19.     }  
  20.    
  21.     struct Edge *e;  
  22.     struct list_t *iter;  
  23.     int *heap = heap_real - 1;  
  24.     int base = 0;  /* euqal to distance[root]  */  
  25.     int size = g->V - 1;  
  26.     int length;  
  27.     do {  
  28.         iter = list_next(&(g->vertices + root)->link);  
  29.         for (; iter; iter = list_next(iter)) {  
  30.             e = list_entry(iter, struct Edge, link);  
  31.             length = base + e->weight;  
  32.             if (length < distance[e->to]) {   
  33.                 HeapDecreaseKey(heap, size,   
  34.                     distance, reflection,   
  35.                     reflection[e->to], length);  
  36.                 parent[e->to] = root;  
  37.             }  
  38.         }  
  39.         root = HeapRemoveTop(heap, size, distance, reflection);  
  40.         base = distance[root];  
  41.    
  42.         if (distance[root] == INFINITY) {   
  43.             /* remain nodes in heap  is not accessible */  
  44.             return g->V - (size + 1); /* 返回強連通分支結點數 */     
  45.         }  
  46.     } while (size);  
  47.    
  48.     /* successfull end algorightm  */  
  49.     return g->V;   
  50. }  

╝④

再獻上一個實現

 

C代碼  收藏代碼
  1.     /*很裸很水的最短路,練習二叉堆優化的Dijstra~ 
  2.  
  3.     之前二叉堆優化的Prim敲了好幾遍前後花了不下八個小時調試還是沒有調試成功, 
  4.     但是還好,熟悉了優先隊列的操作。 
  5.  
  6.     十幾天後的今天重新想起這個,終於調出來了堆優化的Dijstra。理解之後還是蠻簡單的。 
  7.  
  8.     一些寫法並不是最優的,例如heap的實現中可以減少交換元素等。但是有這個自己寫的AC 
  9.     過的Dijkstra在,以後寫二叉堆優化的Prim/Dijkstra和其它優先隊列的題目就可以拿它對照着Debug了。 
  10.  
  11.     2011-07-24 23:00 
  12. */  
  13.   
  14.   
  15. #include <stdio.h>  
  16.   
  17. #define MAXN 1200  
  18. #define MAXM 1200000  
  19. #define INF 19930317  
  20.   
  21. struct node  
  22. {  
  23.     int d, v, p;  
  24. }heap[MAXN];  
  25. int pos[MAXN], hl;  
  26.   
  27. int e[MAXM], cost[MAXM], next[MAXM], g[MAXN], size;  
  28.   
  29. int m, n, s, t;  
  30.   
  31. void insert(int u, int v, int w)  
  32. {  
  33.     e[++size] = v;  
  34.     next[size] = g[u];  
  35.     cost[size] = w;  
  36.     g[u] = size;  
  37. }  
  38.   
  39.   
  40. void swap(int a, int b)  
  41. {  
  42.     heap[0] = heap[a];  
  43.     heap[a] = heap[b];  
  44.     heap[b] = heap[0];  
  45.     pos[heap[a].v] = a;  
  46.     pos[heap[b].v] = b;  
  47. }  
  48.   
  49. void heapfy()  
  50. {  
  51.     int i = 2;  
  52.     while (i <= hl)  
  53.     {  
  54.         if ((i < hl) && (heap[i + 1].d < heap[i].d))  
  55.             i++;  
  56.         if (heap[i].d < heap[i >> 1].d)  
  57.         {  
  58.             swap(i, i >> 1);  
  59.             i <<= 1;  
  60.         }  
  61.         else  
  62.             break;  
  63.     }  
  64. }  
  65.   
  66.   
  67.   
  68. void decrease(int i)  
  69. {  
  70.     while ((i != 1) && (heap[i].d < heap[i >> 1].d))  
  71.     {  
  72.         swap(i, i >> 1);  
  73.         i >>= 1;  
  74.     }  
  75. }  
  76.   
  77. void relax(int u ,int v, int w)  
  78. {  
  79.     if (w + heap[pos[u]].d < heap[pos[v]].d)  
  80.     {  
  81.         heap[pos[v]].p = u;  
  82.         heap[pos[v]].d = w + heap[pos[u]].d;  
  83.         decrease(pos[v]);  
  84.     }  
  85. }  
  86.   
  87. void delete_min()  
  88. {  
  89.     swap(1, hl);  
  90.     hl--;  
  91.     heapfy();  
  92. }  
  93.   
  94. void init()  
  95. {  
  96.     int u ,v ,w, i;  
  97.   
  98.     scanf("%d%d", &m, &n);  
  99.     for (i = 1; i <= m; i++)  
  100.     {  
  101.         scanf("%d%d%d", &u, &v, &w);  
  102.         insert(u, v, w);  
  103.         insert(v, u, w);  
  104.     }  
  105.     s = 1;  
  106.     t = n;  
  107. }  
  108.   
  109.   
  110.   
  111. int dijkstra()  
  112. {  
  113.     int u, p, i;  
  114.   
  115.     for (i = 1; i <= n; i++)  
  116.     {  
  117.         heap[i].v = pos[i] = i;  
  118.         heap[i].d = INF;  
  119.     }  
  120.     heap[s].p = s;  
  121.     heap[s].d = 0;  
  122.     swap(1, s);  
  123.     hl = n;  
  124.     while (hl)  
  125.     {  
  126.         u = heap[1].v;  
  127.         delete_min();  
  128.         p = g[u];  
  129.         while (p)  
  130.         {  
  131.             if (pos[e[p]] <= hl)  
  132.                 relax(u, e[p], cost[p]);  
  133.             p = next[p];  
  134.         }  
  135.   
  136.     }  
  137. }  
  138. int main()  
  139. {  
  140.     init();  
  141.     dijkstra();  
  142.     printf("%d\n", heap[pos[t]].d);  
  143.     return 0;  
  144. }  

 ╝③

菲波那契堆實現

用類似的方法,使用Fibonacci Heap可以將複雜度降到O(E+VlogV),但實現比較麻煩。因此這裏暫不列舉。

 

╝②

 

最短路徑算法之Bellman-Ford算法

 

§2 Bellman-Ford算法

 

Bellman-Ford算法思想

Bellman-Ford算法能在更普遍的情況下(存在負權邊)解決單源點最短路徑問題。對於給定的帶權(有向或無向)圖 G=(V,E),其源點爲s,加權函數 w是 邊集 E 的映射。對圖G運行Bellman-Ford算法的結果是一個布爾值,表明圖中是否存在着一個從源點s可達的負權迴路。若不存在這樣的迴路,算法將給出從源點s到 圖G的任意頂點v的最短路徑d[v]。

 

Bellman-Ford算法流程:

(1)    初始化:將除源點外的所有頂點的最短距離估計值 d[v] ←+∞, d[s] ←0;

(2)    迭代求解:反覆對邊集E中的每條邊進行鬆弛操作,使得頂點集V中的每個頂點v的最短距離估計值逐步逼近其最短距離;(運行|v|-1次)

(3)    檢驗負權迴路:判斷邊集E中的每一條邊的兩個端點是否收斂。如果存在未收斂的頂點,則算法返回false,表明問題無解;否則算法返回true,並且從源點可達的頂點v的最短距離保存在 d[v]中。

算法描述如下:

Bellman-Ford(G,w,s) :boolean   //圖G ,邊集 函數 w ,s爲源點

1        for each vertex v ∈ V(G) do        //初始化 1階段

2            d[v] ←+∞

3        d[s] ←0;                             //1階段結束

4        for i=1 to |v|-1 do               //2階段開始,雙重循環。

5           for each edge(u,v) ∈E(G) do //邊集數組要用到,窮舉每條邊。

6              If d[v]> d[u]+ w(u,v) then      //鬆弛判斷

7                 d[v]=d[u]+w(u,v)               //鬆弛操作   2階段結束

8        for each edge(u,v) ∈E(G) do

9            If d[v]> d[u]+ w(u,v) then

10            Exit false

11    Exit true

 

下面給出描述性證明:

   首先指出,圖的任意一條最短路徑既不能包含負權迴路,也不會包含正權迴路,因此它最多包含|v|-1條邊。

   其次,從源點s可達的所有頂點如果 存在最短路徑,則這些最短路徑構成一個以s爲根的最短路徑樹。Bellman-Ford算法的迭代鬆弛操作,實際上就是按頂點距離s的層次,逐層生成這棵最短路徑樹的過程。

   在對每條邊進行1遍鬆弛的時候,生成了從s出發,層次至多爲1的那些樹枝。也就是說,找到了與s至多有1條邊相聯的那些頂點的最短路徑;對每條邊進行第2遍鬆弛的時候,生成了第2層次的樹枝,就是說找到了經過2條邊相連的那些頂點的最短路徑……。因爲最短路徑最多隻包含|v|-1 條邊,所以,只需要循環|v|-1 次。

每實施一次鬆弛操作,最短路徑樹上就會有一層頂點達到其最短距離,此後這層頂點的最短距離值就會一直保持不變,不再受後續鬆弛操作的影響。(但是,每次還要判斷鬆弛,這裏浪費了大量的時間,怎麼優化?單純的優化是否可行?)

   如果沒有負權迴路,由於最短路徑樹的高度最多隻能是|v|-1,所以最多經過|v|-1遍鬆弛操作後,所有從s可達的頂點必將求出最短距離。如果 d[v]仍保持 +∞,則表明從s到v不可達。

如果有負權迴路,那麼第 |v|-1 遍鬆弛操作仍然會成功,這時,負權迴路上的頂點不會收斂。

╝⑥

Bellman-Ford算法實現

 

Cpp代碼  收藏代碼
  1. #include<iostream>  
  2. #include<cstdio>  
  3. using namespace std;  
  4.   
  5. #define MAX 0x3f3f3f3f  
  6. #define N 1010  
  7. int nodenum, edgenum, original; //點,邊,起點  
  8. typedef struct Edge //邊  
  9. {  
  10.     int u, v;  
  11.     int cost;  
  12. }Edge;  
  13. Edge edge[N];  
  14. int dis[N], pre[N];  
  15. bool Bellman_Ford()  
  16. {  
  17.     for(int i = 1; i <= nodenum; ++i) //初始化  
  18.         dis[i] = (i == original ? 0 : MAX);  
  19.     for(int i = 1; i <= nodenum - 1; ++i)  
  20.         for(int j = 1; j <= edgenum; ++j)  
  21.             if(dis[edge[j].v] > dis[edge[j].u] + edge[j].cost) //鬆弛(順序一定不能反~)  
  22.             {  
  23.                 dis[edge[j].v] = dis[edge[j].u] + edge[j].cost;  
  24.                 pre[edge[j].v] = edge[j].u;  
  25.             }  
  26.             bool flag = 1; //判斷是否含有負權迴路  
  27.             for(int i = 1; i <= edgenum; ++i)  
  28.                 if(dis[edge[i].v] > dis[edge[i].u] + edge[i].cost)  
  29.                 {  
  30.                     flag = 0;  
  31.                     break;  
  32.                 }  
  33.                 return flag;  
  34. }  
  35.   
  36. void print_path(int root) //打印最短路的路徑(反向)  
  37. {  
  38.     while(root != pre[root]) //前驅  
  39.     {  
  40.         printf("%d-->", root);  
  41.         root = pre[root];  
  42.     }  
  43.     if(root == pre[root])  
  44.         printf("%d\n", root);  
  45. }  
  46.   
  47. int main()  
  48. {  
  49.     scanf("%d%d%d", &nodenum, &edgenum, &original);  
  50.     pre[original] = original;  
  51.     for(int i = 1; i <= edgenum; ++i)  
  52.     {  
  53.         scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].cost);  
  54.     }  
  55.     if(Bellman_Ford())  
  56.         for(int i = 1; i <= nodenum; ++i) //每個點最短路  
  57.         {  
  58.             printf("%d\n", dis[i]);  
  59.             printf("Path:");  
  60.             print_path(i);  
  61.         }  
  62.     else  
  63.         printf("have negative circle\n");  
  64.     return 0;  
  65. }  

 ╝⑦

 

Bellman-Ford算法優化——SPFA算法

 

循環的提前跳出:在實際操作中,貝爾曼-福特算法經常會在未達到V-1次前就出解,V-1其實是最大值。於是可以在循環中設置判定,在某次循環不再進行鬆弛時,直接退出循環,進行負權環判定。

具體做法是用一個隊列保存待鬆弛的點,然後對於每個出隊的點依次遍歷每個與他有邊相鄰的點(用鄰接表效率較高),如果該點可以鬆弛並且隊列中沒有該點則將它加入隊列中(只有進行鬆弛操作的點纔會對它的鄰接點有影響,也就是說其鄰接點才需要鬆弛操作),如此迭代直到隊列爲空。

 

SPFA算法實現

 

Cpp代碼  收藏代碼
  1. #include <iostream>  
  2. #include <queue>  
  3. using namespace std;  
  4. const long MAXN=10000;  
  5. const long lmax=0x7FFFFFFF;  
  6. typedef struct    
  7. {  
  8.     long v;  
  9.     long next;  
  10.     long cost;  
  11. }Edge;  
  12. Edge e[MAXN];  
  13. long p[MAXN];  
  14. long Dis[MAXN];  
  15. bool vist[MAXN];  
  16. queue<long> q;  
  17. long m,n;//點,邊  
  18. void init()  
  19. {  
  20.     long i;  
  21.     long eid=0;  
  22.     memset(vist,0,sizeof(vist));  
  23.     memset(p,-1,sizeof(p));  
  24.     fill(Dis,Dis+MAXN,lmax);  
  25.     while (!q.empty())  
  26.     {  
  27.         q.pop();  
  28.     }  
  29.     for (i=0;i<n;++i)  
  30.     {  
  31.         long from,to,cost;  
  32.         scanf("%ld %ld %ld",&from,&to,&cost);  
  33.         e[eid].next=p[from];  
  34.         e[eid].v=to;  
  35.         e[eid].cost=cost;  
  36.         p[from]=eid++;  
  37.         //以下適用於無向圖  
  38.         swap(from,to);  
  39.         e[eid].next=p[from];  
  40.         e[eid].v=to;  
  41.         e[eid].cost=cost;  
  42.         p[from]=eid++;  
  43.     }  
  44. }  
  45. void print(long End)  
  46. {  
  47.     //若爲lmax 則不可達  
  48.     printf("%ld\n",Dis[End]);      
  49. }  
  50. void SPF()  
  51. {  
  52.     init();  
  53.     long Start,End;  
  54.     scanf("%ld %ld",&Start,&End);  
  55.     Dis[Start]=0;  
  56.     vist[Start]=true;  
  57.     q.push(Start);  
  58.     while (!q.empty())  
  59.     {  
  60.         long t=q.front();  
  61.         q.pop();  
  62.         vist[t]=false;  
  63.         long j;  
  64.         for (j=p[t];j!=-1;j=e[j].next)  
  65.         {  
  66.             long w=e[j].cost;  
  67.             if (w+Dis[t]<Dis[e[j].v])  
  68.             {  
  69.                 Dis[e[j].v]=w+Dis[t];  
  70.                 if (!vist[e[j].v])  
  71.                 {  
  72.                     vist[e[j].v]=true;  
  73.                     q.push(e[j].v);  
  74.                 }  
  75.             }  
  76.         }  
  77.     }  
  78.     print(End);  
  79. }  
  80. int main()  
  81. {  
  82.     while (scanf("%ld %ld",&m,&n)!=EOF)  
  83.     {  
  84.         SPF();  
  85.     }  
  86.     return 0;  
  87.   
  88. }  

╝⑧

 

最短路徑算法之Floyd-Warshall算法

 

§3 Floyd-Warshall算法

 

Floyd-Warshall算法是解決任意兩點間的最短路徑的算法,可以處理有向圖或負權值的最短路徑問題,同時也被用於計算有向圖的傳遞閉包。算法的時間複雜度爲O(n³),空間複雜度爲O(n²)。

Floyd-Warshall算法的原理是動態規劃

D_{i,j,k}爲從ij的只以(1..k)集合中的節點爲中間節點的最短路徑的長度。

  1. 若最短路徑經過點k,則D_{i,j,k}=D_{i,k,k-1}+D_{k,j,k-1}
  2. 若最短路徑不經過點k,則D_{i,j,k}=D_{i,j,k-1}

因此,D_{i,j,k}=\mbox{min}(D_{i,k,k-1}+D_{k,j,k-1},D_{i,j,k-1})

在實際算法中,爲了節約空間,可以直接在原來空間上進行迭代,這樣空間可降至二維。

╝⑨

Floyd-Warshall算法實現

C代碼  收藏代碼
  1. for(int k =1 ;  k <= n ; k ++ ){  
  2.     for(int i =1 ; i<= n ; i++){  
  3.         for(int j =1 ;j<=n;j++){  
  4.                dist[ i ][ j ]= min( dist[ i ][ j ],dist[ i ][ k ]+dist[ k ][ j ] );        
  5.           }  
  6.      }  
  7. }  

如果dist[i][k]或者dist[k][j]不存在,程序中用∞代替。

真正的Floyd算法是一種基於DP(Dynamic Programming)的最短路徑算法。

  設圖G中n 個頂點的編號爲1到n。令c [i, j, k]表示從i 到j 的最短路徑的長度,其中k 表示該路徑中的最大頂點,也就是說c[i,j,k]這條最短路徑所通過的中間頂點最大不超過k。因此,如果G中包含邊<i, j>,則c[i, j, 0] =邊<i, j> 的長度;若i= j ,則c[i,j,0]=0;如果G中不包含邊<i, j>,則c (i, j, 0)= +∞。c[i, j, n] 則是從i 到j 的最短路徑的長度。

  對於任意的k>0,通過分析可以得到:中間頂點不超過k 的i 到j 的最短路徑有兩種可能:該路徑含或不含中間頂點k。若不含,則該路徑長度應爲c[i, j, k-1],否則長度爲 c[i, k, k-1] +c [k, j, k-1]。c[i, j, k]可取兩者中的最小值。

  狀態轉移方程:c[i, j, k]=min{c[i, j, k-1], c [i, k, k-1]+c [k, j, k-1]},k>0。

  這樣,問題便具有了最優子結構性質,可以用動態規劃方法來求解。

Cpp代碼  收藏代碼
  1. #include <iostream>  
  2.  2 using namespace std;  
  3.  3   
  4.  4 const int INF = 100000;  
  5.  5 int n=10,map[11][11],dist[11][11][11];  
  6.  6 void init(){  
  7.  7     int i,j;  
  8.  8     for(i=1;i<=n;i++)  
  9.  9         for(j=1;j<=n;j++)  
  10. 10             map[i][j]=(i==j)?0:INF;  
  11. 11     map[1][2]=2,map[1][4]=20,map[2][5]=1;  
  12. 12     map[3][1]=3,map[4][3]=8,map[4][6]=6;  
  13. 13     map[4][7]=4,map[5][3]=7,map[5][8]=3;  
  14. 14     map[6][3]=1,map[7][8]=1,map[8][6]=2;  
  15. 15     map[8][10]=2,map[9][7]=2,map[10][9]=1;  
  16. 16 }  
  17. 17 void floyd_dp(){  
  18. 18     int i,j,k;  
  19. 19     for(i=1;i<=n;i++)  
  20. 20         for(j=1;j<=n;j++)  
  21. 21             dist[i][j][0]=map[i][j];  
  22. 22     for(k=1;k<=n;k++)  
  23. 23         for(i=1;i<=n;i++)  
  24. 24             for(j=1;j<=n;j++){  
  25. 25                 dist[i][j][k]=dist[i][j][k-1];  
  26. 26                 if(dist[i][k][k-1]+dist[k][j][k-1]<dist[i][j][k])  
  27. 27                     dist[i][j][k]=dist[i][k][k-1]+dist[k][j][k-1];  
  28. 28             }  
  29. 29 }  
  30. 30 int main(){  
  31. 31     int k,u,v;  
  32. 32     init();  
  33. 33     floyd_dp();  
  34. 34     while(cin>>u>>v,u||v){  
  35. 35         for(k=0;k<=n;k++){  
  36. 36             if(dist[u][v][k]==INF) cout<<"+∞"<<endl;  
  37. 37             else cout<<dist[u][v][k]<<endl;  
  38. 38         }  
  39. 39     }  
  40. 40     return 0;  
  41. 41 }   

╝⑨

 

最短路徑算法之Johnson算法

 

§4 Johnson算算法

 

 

Johson算法是目前最高效的在無負環可帶負權重的網絡中求所有點對最短路徑的算法. Johson算法是Bellman-Ford算法, Reweighting(重賦權重)和Dijkstra算法的大綜合. 對每個頂點運用Dijkstra算法的時間開銷決定了Johnson算法的時間開銷. 每次Dijkstra算法(d堆PFS實現)的時間開銷是O( E * lgd(V) ). 其中E爲邊數, V爲頂點數, d爲採用d路堆實現優先隊列ADT. 所以, 此種情況下Johnson算法的時間複雜度是O( V * E * lgd(V) )。

 

Johnson算法具體步驟(翻譯自wikipedia):

1.初始化,把一個node q添加到圖G中,使node q 到圖G每一個點的權值爲0。

2.使用Bellman-Ford算法,從源點爲q,尋找每一個點 v從q到v的最短路徑h(v),如果存在負環的話,算法終止。

3.使用第2步驟中Bellman-Ford計算的最短路徑值對原來的圖進行reweight操作(重賦值):邊<u,v>的權值w(u,v),修改成w(u,v)+h(u)-h(v)。

4.最後,移去q,針對新圖(重賦值之後的圖)使用Dijkstra算法計算從每一個點s到其餘另外點的最短距離。

╝⑩

Johnson算法實現:

 

Cpp代碼  收藏代碼
  1. #include "stdafx.h"  
  2. #include<iostream>  
  3. #define Infinity 65535  
  4. #define MAX 100  
  5. using namespace std;  
  6. //邊尾節點結構體  
  7. struct edgeNode  
  8. {  
  9. int no;//節點序號  
  10. int weight; //此邊權值  
  11. edgeNode *next; //下一條鄰接邊  
  12. };  
  13. //節點信息  
  14. struct vexNode  
  15. {  
  16. char info; //節點序號  
  17. edgeNode *link; //與此節點爲首節點的邊的尾節點鏈表  
  18. };  
  19. //優先隊列元素結構體  
  20. struct PriQue  
  21. {  
  22. int no; //節點元素序號  
  23. int weight; //源點到此節點的權值  
  24. };  
  25. //節點數組  
  26. vexNode adjlist[MAX];  
  27. //添加一個序號爲0節點到其他各節點的最小權值  
  28. int d[MAX];  
  29. //源點到各節點的最小權值  
  30. int lowcost[MAX];  
  31. //各節點對間的最小權值  
  32. int mincost[MAX][MAX];  
  33. //優先隊列  
  34. PriQue queue[2*MAX];  
  35. //建立圖的鄰接表  
  36. void createGraph(vexNode *adjlist,int n,int e)  
  37. {  
  38. int i;  
  39. cout<<"請輸入這些節點的信息:"<<endl;  
  40. for(i=1;i<=n;i++)  
  41. {  
  42. cout<<"節點"<<i<<"的名稱:";  
  43. cin>>adjlist[i].info;  
  44. adjlist[i].link = NULL;  
  45. }  
  46. cout<<"請輸入這些邊的信息:"<<endl;  
  47. int v1,v2;  
  48. edgeNode *p1;  
  49. int weight1;  
  50. for(i=1;i<=e;i++)  
  51. {  
  52. cout<<"邊"<<i<<"的首尾節點:";  
  53. cin>>v1>>v2;  
  54. cout<<"請輸入此邊的權值:";  
  55. cin>>weight1;  
  56. p1 = (edgeNode*)malloc(sizeof(edgeNode));  
  57. p1->no = v2;  
  58. p1->weight = weight1;  
  59. p1->next = adjlist[v1].link;  
  60. adjlist[v1].link = p1;  
  61. }  
  62. //添加節點0,到每一個節點的距離都是0  
  63. adjlist[0].info ='0';  
  64. adjlist[0].link = NULL;  
  65. for(i=n;i>=1;i--)  
  66. {  
  67. d[i] = 0;  
  68. p1 = (edgeNode*)malloc(sizeof(edgeNode));  
  69. p1->no = i;  
  70. p1->weight = 0;  
  71. p1->next = adjlist[0].link;  
  72. adjlist[0].link = p1;  
  73. }  
  74. }  
  75. //bellman_ford算法求節點0到其他各節點的最短距離  
  76. bool bellman_ford(vexNode *adjlist,int *d,int n)  
  77. {  
  78. int i,j;  
  79. d[0] = 0;  
  80. edgeNode *p1;  
  81. for(j=1;j<=n;j++)  
  82. {  
  83. for(i=0;i<=n;i++)  
  84. {  
  85. p1= adjlist[i].link;  
  86. while(p1 != NULL)  
  87. {  
  88. if(d[p1->no]>d[i]+p1->weight)  
  89. d[p1->no] = d[i] + p1->weight;  
  90. p1 = p1->next;  
  91. }  
  92. }  
  93. }  
  94. for(i=0;i<=n;i++)  
  95. {  
  96. p1= adjlist[i].link;  
  97. while(p1 != NULL)  
  98. {  
  99. if(d[p1->no]>d[i]+p1->weight)  
  100. return false;  
  101. p1 = p1->next;  
  102. }  
  103. }  
  104. return true;  
  105. }  
  106. //johnson算法中,需要對每一條邊重新賦權值產生非負的權  
  107. void G_w_to_G1_w1(int *d,const int n)  
  108. {  
  109. int i;  
  110. edgeNode *p1;  
  111. for(i=0;i<=n;i++)  
  112. {  
  113. p1= adjlist[i].link;  
  114. while(p1 != NULL)  
  115. {  
  116. p1->weight = p1->weight + d[i] - d[p1->no];  
  117. p1 = p1->next;  
  118. }  
  119. }  
  120. }  
  121. //保持優先隊列的優先性,以指定源點到每一點的最少距離爲關鍵字  
  122. void keep_heap(PriQue *queue,int &num,int i)  
  123. {  
  124. int smallest = i;  
  125. int left = 2*i,right = 2*i+1;  
  126. if(left<=num&&queue[left].weight<queue[i].weight)  
  127. smallest = left;  
  128. if(right<=num&&queue[right].weight<queue[smallest].weight)  
  129. smallest = right;  
  130. if(smallest != i)  
  131. {  
  132. PriQue q = queue[smallest];  
  133. queue[smallest] = queue[i];  
  134. queue[i] = q;  
  135. keep_heap(queue,num,smallest);  
  136. }  
  137. }  
  138. //插入一個元素到優先隊列中,並保持隊列優先性  
  139. void insert_heap(PriQue *queue,int &num,int no,int wei)  
  140. {  
  141. num += 1;  
  142. queue[num].no = no;  
  143. queue[num].weight = wei;  
  144. int i = num;  
  145. while(i>1&&queue[i].weight<queue[i/2].weight)  
  146. {  
  147. PriQue q1;  
  148. q1 = queue[i/2];  
  149. queue[i/2] = queue[i];  
  150. queue[i] = q1;  
  151. i = i/2;  
  152. }  
  153. }  
  154. //取出隊列首元素  
  155. PriQue heap_extract_min(PriQue *queue,int &num)  
  156. {  
  157. if(num<1)  
  158. return queue[0];  
  159. PriQue que = queue[1];  
  160. queue[1] = queue[num];  
  161. num = num -1;  
  162. keep_heap(queue,num,1);  
  163. return que;  
  164. }  
  165. //dijkstra算法求節點i到其他每一個節點的最短距離  
  166. void dijkstra(vexNode *adjlist,PriQue * queue,int i,const int n,int &num)  
  167. {  
  168. int v = i;  
  169. //lowcost[v] = 0;  
  170. int j;  
  171. for(j=1;j<n;j++)  
  172. {  
  173. edgeNode *p1 = adjlist[v].link;  
  174. while(p1 != NULL)  
  175. {  
  176. if(lowcost[p1->no] > lowcost[v] + p1->weight)  
  177. {  
  178. lowcost[p1->no] = lowcost[v] + p1->weight;  
  179. insert_heap(queue,num,p1->no,lowcost[p1->no]);  
  180. }  
  181. p1 = p1->next;  
  182. }  
  183. v = heap_extract_min(queue,num).no;  
  184. if(v==0)  
  185. {  
  186. cout<<"隊列中沒有節點!"<<endl;  
  187. return;  
  188. }  
  189. }  
  190. }  
  191.   
  192. int _tmain(int argc, _TCHAR* argv[])  
  193. {  
  194. int cases;  
  195. cout<<"請輸入案例的個數:";  
  196. cin>>cases;  
  197. //用隊列0元素作爲哨兵,如果隊列中沒有元素,則返回隊列0元素  
  198. queue[0].no = 0;  
  199. queue[0].weight = 0;  
  200. while(cases--)  
  201. {  
  202. int n,e;  
  203. cout<<"請輸入節點數:";  
  204. cin>>n;  
  205. cout<<"請輸入邊數:";  
  206. cin>>e;  
  207. //隊列中的元素,初始爲0  
  208. int num = 0;  
  209. int i,j;  
  210. //創建鄰接表  
  211. createGraph(adjlist,n,e);  
  212. cout<<endl;  
  213. memset(d,Infinity,sizeof(d));  
  214. //bellman_ford算法求節點0到其他各節點的最短距離  
  215. bool flag = bellman_ford(adjlist,d,n);  
  216. if(!flag)  
  217. {  
  218. cout<<"此圖存在負迴路,不正確!"<<endl;  
  219. continue;  
  220. }  
  221. //johnson算法中,需要對每一條邊重新賦權值產生非負的權  
  222. G_w_to_G1_w1(d,n);  
  223. //運用dijkstra算法求得每一對節點間的最短距離  
  224. for(i=1;i<=n;i++)  
  225. {  
  226. for(j=1;j<=n;j++)  
  227. lowcost[j] = Infinity;  
  228. lowcost[i] =0;  
  229. dijkstra(adjlist,queue,i,n,num);  
  230. //重新把原值賦值回來,因爲在函數G_w_to_G1_w1()中改變過  
  231. for(j=1;j<=n;j++)  
  232. mincost[i][j] = lowcost[j] + d[j] - d[i];  
  233. }  
  234. cout<<"下面輸出每一對頂點之間的最短距離:"<<endl;  
  235. for(i=1;i<=n;i++)  
  236. for(j=1;j<=n;j++)  
  237. {  
  238. cout<<"頂點("<<i<<":"<<adjlist[i].info<<")到頂點("<<j<<":"<<adjlist[j].info<<")的最短距離爲:"<<mincost[i][j]<<endl;  
  239. }  
  240. }  
  241. system("pause");  
  242. return 0;  
  243. }  

 

 

╝⑩+1

 

§5 問題歸約

對於兩個問題A和B,如果使用求解B的一個算法來開發一個求解A的算法,且最壞的情況下算法總時間不會超過最壞情況下求解B的算法運行時間的常量倍,則稱問題A可歸約(reduce)爲問題B。

 

1.傳遞閉包問題可歸約爲有非負權值的所有對最短路徑問題。

給定兩點u和v,有向圖中從u到v存在一條路徑,當且僅當網中從u到v的路徑長度非零。

 

2.在邊權沒有限制的網中,(單源點或所有對)最長路徑和最短路徑問題是等價的。

 

3.作業調度問題可歸約爲差分約束問題。

 

4.有正常數的差分約束問題等價於無環網中的單源點最長路徑。

 

5.帶有截止期的作業調度問題可歸約爲(允許帶有負權值的)最短路徑問題。

╝⑩+2

 

§6 最短路徑的擴展與應用

1.k短路

 

2.差分約束系統

 

3.DAG圖上的單源點最短路徑

 

4.Flyod求最小環

 

§6 小結

 

這篇文章把最短路徑的四個算法——Dijkstra,Bellman-Ford,Floyd-Warshall,Johnson從原理到步驟,再從流程到實現都將了,有了一定的認識和理解。如果你有任何建議或者批評和補充,請留言指出,不勝感激,更多參考請移步互聯網。

 

 

參考:

 

永遠的綠巖:http://2728green-rock.blog.163.com/blog/static/43636790200901211848284/

②NOCOW:http://www.nocow.cn/index.php/Dijkstra%E7%AE%97%E6%B3%95

oa414http://www.cnblogs.com/oa414/archive/2011/07/25/2115858.html

④NOCOW:http://www.nocow.cn/index.php/Dijkstra_%E4%BA%8C%E5%8F%89%E5%A0%86%E5%AE%9E%E7%8E%B0_C

IT_元帥http://www.cnblogs.com/newwy/archive/2010/11/20/1882569.html

⑥infinity:http://www.cppblog.com/infinity/archive/2008/11/11/66621.html

niushuai666http://blog.csdn.net/niushuai666/article/details/6791765

Losthttp://www.cnblogs.com/zhuangli/archive/2008/07/26/1251869.html

極限定律http://www.cppblog.com/mythit/archive/2009/04/21/80579.html

⑩wikipedia:http://en.wikipedia.org/wiki/Johnson's_algorithm

⑩+1pleasetojava:http://pleasetojava.iteye.com/blog/1270377

⑩+2Robert Sedgewick:Algorithm in C


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章