1. 程式人生 > >18.boost Ford最短路徑算法(效率低)

18.boost Ford最短路徑算法(效率低)

最短路 amp 頂點 oid cout bsp 算法 圖片 trait

技術分享圖片

到某個節點最近距離 最短路徑當前節點的父節點

完整代碼

 1 #include <iostream>
 2 #include <string>
 3 #include <utility>
 4 #include <vector>
 5 #include <deque>
 6 #include <boost/graph/adjacency_list.hpp>
 7 //A*尋路算法
 8 #include <boost\graph\astar_search.hpp>
 9 //dijsktra
10 #include <boost\graph\dijkstra_shortest_paths.hpp> 11 //bellman-Ford算法 12 #include <boost\graph\bellman_ford_shortest_paths.hpp> 13 using namespace std; 14 using namespace boost; 15 16 17 void main() 18 { 19 //定義節點和邊的相關對象和屬性 20 enum { u, v, x, y, z, N }; 21 char name[] = { u
, v, x, y, z }; 22 typedef std::pair < int, int >E; 23 E edge_array[] = { E(u, y), E(u, x), E(u, v), E(v, u), 24 E(x, y), E(x, v), E(y, v), E(y, z), E(z, u), E(z, x) }; 25 int weights[] = { -4, 8, 5, -2, 9, -3, 7, 2, 6, 7 }; 26 int num_arcs = sizeof(edge_array) / sizeof
(E); 27 28 //定義所用的圖種類和相關類型 29 typedef adjacency_list < vecS, vecS, directedS, 30 no_property, property < edge_weight_t, int > > Graph; 31 //生成圖對象 32 Graph g(edge_array, edge_array + num_arcs, weights, N); 33 graph_traits < Graph >::edge_iterator ei, ei_end; 34 35 //distance用於放置依近到遠的路徑距離 36 std::vector<int> distance(N, (std::numeric_limits < short >::max)()); 37 //parent用於放置最短路徑生成樹的各個頂點的父節點 38 std::vector<std::size_t> parent(N); 39 for (int i = 0; i < N; ++i) 40 parent[i] = i; 41 42 43 //將源點z對應距離設為0 44 distance[z] = 0; 45 //應用Bellman-Ford算法 46 bool r = bellman_ford_shortest_paths 47 (g, int(N), weight_map(get(edge_weight, g)).distance_map(&distance[0]). 48 predecessor_map(&parent[0])); 49 50 if (r) 51 { 52 std::cout << "源點z到各點的最短路徑\n"; 53 std::cout << "目的點\t" << "最短路徑\t" << "最短路徑樹的父節點:\n"; 54 for (int i = 0; i < N; ++i) 55 std::cout << name[i] << ": \t" << distance[i] 56 << "\t\t" << name[parent[i]] << std::endl; 57 } 58 else 59 std::cout << "negative cycle" << std::endl; 60 61 system("pause"); 62 }

18.boost Ford最短路徑算法(效率低)