Programming Algorithm-single-source shortest path Bellman-Ford code (c)

Source: Internet
Author: User
Single-source shortest path problem Bellman-Ford code (c)


Address: http://blog.csdn.net/caroline_wendy


Single-Source Shortest Path: fix a starting point and find the shortest path to all other points.


Bellman-Ford: Set the shortest length from the current vertex I to d [I], and set the initial value D [s] = 0, d [I] = inf,

Continue to use recursive relationshipsD [E. To] = d [E. From] + E. CostUpdate the value of D.

Time Complexity: O (V * E)


Code:

/* * 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;}

Output:

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








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.