編程演算法 - 單源最短路問題 Bellman-Ford 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   單源最短路   bellman-ford   代碼   

單源最短路問題 Bellman-Ford 代碼(C)


本文地址: http://blog.csdn.net/caroline_wendy


單源最短路: 固定一個起點, 求它到其他所有點的最短路的問題.


Bellman-Ford: 設當前到頂點i的最短路長度為d[i], 並設初值d[s]=0, d[i]=INF, 

再不斷使用遞推關係式d[e.to] = d[e.from] + e.cost更新d的值.

時間複雜度: O(V*E)


代碼:

/* * CppPrimer.cpp * *  Created on: 2013.11.12 *      Author: Caroline *//*eclipse cdt*/#include <stdio.h>#include <limits.h>#include <vector>using namespace std;class Program {static const int MAX_V = 100;static const int MAX_E = 100;const int INF = INT_MAX>>2;struct edge {int from, to, cost; };edge es[MAX_E] = {{0,1,2}, {0,2,5},{1,0,2}, {1,2,4}, {1,3,6}, {1,4,10},{2,0,5}, {2,1,4}, {2,3,2},{3,2,2}, {3,1,6}, {3,5,1},{4,1,10}, {4,5,3}, {4,6,5},{5,3,1}, {5,4,3}, {5,6,9},{6,4,5}, {6,5,9}};int V = 7, E = 20;public:int d[MAX_V];void shortest_path(int s) {for (int i=0; i<V; ++i) d[i] = INF;d[s] = 0;while (true) {bool update = false;for (int i=0; i<E; i++) {edge e = es[i];if (d[e.from] != INF && d[e.to] > d[e.from] + e.cost) {d[e.to] = d[e.from] + e.cost;update = true;}}if (!update) break;}}};int main (void){Program iP;iP.shortest_path(0);for (int i=0; i<7; i++) {printf("%d = %d\n", i, iP.d[i]);}return 0;}

輸出:

0 = 01 = 22 = 53 = 74 = 115 = 86 = 16








相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.