18.boost Ford最短路径算法(效率低)
Posted 喵小喵~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了18.boost Ford最短路径算法(效率低)相关的知识,希望对你有一定的参考价值。
到某个节点最近距离 最短路径当前节点的父节点
完整代码
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最短路径算法(效率低)的主要内容,如果未能解决你的问题,请参考以下文章
求最短路径的三种算法: Ford, Dijkstra和Floyd