21.boost Ford最短路径算法(效率低)

本文介绍了一种使用Bellman-Ford算法寻找带负权边的加权图中从源点到所有其他点的最短路径的方法。通过C++代码实现了算法,并展示了如何通过该算法检测是否存在负权回路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

到某个节点最近距离                  最短路径当前节点的父节点

完整代码

 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 }

 

转载于:https://www.cnblogs.com/xiaochi/p/8673287.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值