服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++计算任意权值的单源最短路径(Bellman-Ford)

C++计算任意权值的单源最短路径(Bellman-Ford)

2021-09-02 15:45ChanJose C/C++

这篇文章主要为大家详细介绍了C++计算任意权值的单源最短路径,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C++计算任意权值单源最短路径的具体代码,供大家参考,具体内容如下

一、有Dijkstra算法求最短路径了,为什么还要用Bellman-Ford算法

Dijkstra算法不适合用于带有负权值的有向图。

如下图:

C++计算任意权值的单源最短路径(Bellman-Ford)

用Dijkstra算法求顶点0到各个顶点的最短路径:

(1)首先,把顶点0添加到已访问顶点集合S中,选取权值最小的邻边<0, 2>,权值为5

记录顶点2的最短路径为:dist[2]=5, path[2]=0,把顶点2添加到集合S中。

顶点2,没有邻边(从顶点2出发,其他顶点为终点的边),结束;

(2)访问<0, 1>边,权值为7,把顶点7添加到顶点集合S中,dist[1]=7, path[1]=0。

虽然,顶点1有邻边<1,2>,但是因为顶点2已在集合S中,所以,不继续修改,结束程序。

所以,最终dist[1]=7,dist[2]=5。显然结果不对,顶点2的最短路径应为:0->1->2,权值为7+(-5)=2

二、Bellman-Ford算法思路:

Bellman-Ford算法,效率低,但是适合用于求带有负权值的单源最短路径。

不考虑有回路的,如下图,顶点0到顶点1的最短路径可以无穷小

C++计算任意权值的单源最短路径(Bellman-Ford)

下面开始简单描述Bellman-Ford的思路:

C++计算任意权值的单源最短路径(Bellman-Ford) C++计算任意权值的单源最短路径(Bellman-Ford)

C++计算任意权值的单源最短路径(Bellman-Ford)

可以,看到:通过绕过一些顶点,可以取得更短的路径长度

当k=1时,即从源点(顶点0)到其他顶点,只需要一条边。有<0,1>、<0,2>、<0,3>,所以有:dist[1]=6,dist[2]=5,dist[3]=5;

当k=2时,需要2条边的,u=1,有0->2->3,长度为:5+(-2)=3, 更短,所以要修改dist[1]=3;

u=2,有:0->3->2,长度为:5+(-2)=3,更短,所以要修改dist[2]=3;

u=3,没有两条边从顶点0到达顶点3的路径;

u=4,有0->1->4,长度为:6+(-1)=5, 更短,所以要修改dist[4]=5;

u=5,有0->3->5,长度为:5+(-1)=4,更短,所以要修改dist[5]=4;

u=6,没有2条边就可以从顶点0到顶点6的路径。

重复上面步骤,直到k=n-1结束程序。

C++计算任意权值的单源最短路径(Bellman-Ford)

三、实现程序:

1.Graph.h:有向图

  1. #ifndef Graph_h
  2. #define Graph_h
  3.  
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. const int DefaultVertices = 30;
  8.  
  9. template <class T, class E>
  10. struct Edge { // 边结点的定义
  11. int dest; // 边的另一顶点位置
  12. E cost; // 表上的权值
  13. Edge<T, E> *link; // 下一条边链指针
  14. };
  15.  
  16. template <class T, class E>
  17. struct Vertex { // 顶点的定义
  18. T data; // 顶点的名字
  19. Edge<T, E> *adj; // 边链表的头指针
  20. };
  21.  
  22. template <class T, class E>
  23. class Graphlnk {
  24. public:
  25. const E maxValue = 100000; // 代表无穷大的值(=∞)
  26. Graphlnk(int sz=DefaultVertices); // 构造函数
  27. ~Graphlnk(); // 析构函数
  28. void inputGraph(); // 建立邻接表表示的图
  29. void outputGraph(); // 输出图中的所有顶点和边信息
  30. T getValue(int i); // 取位置为i的顶点中的值
  31. E getWeight(int v1, int v2); // 返回边(v1, v2)上的权值
  32. bool insertVertex(const T& vertex); // 插入顶点
  33. bool insertEdge(int v1, int v2, E weight); // 插入边
  34. bool removeVertex(int v); // 删除顶点
  35. bool removeEdge(int v1, int v2); // 删除边
  36. int getFirstNeighbor(int v); // 取顶点v的第一个邻接顶点
  37. int getNextNeighbor(int v,int w); // 取顶点v的邻接顶点w的下一邻接顶点
  38. int getVertexPos(const T vertex); // 给出顶点vertex在图中的位置
  39. int numberOfVertices(); // 当前顶点数
  40. private:
  41. int maxVertices; // 图中最大的顶点数
  42. int numEdges; // 当前边数
  43. int numVertices; // 当前顶点数
  44. Vertex<T, E> * nodeTable; // 顶点表(各边链表的头结点)
  45. };
  46.  
  47. // 构造函数:建立一个空的邻接表
  48. template <class T, class E>
  49. Graphlnk<T, E>::Graphlnk(int sz) {
  50. maxVertices = sz;
  51. numVertices = 0;
  52. numEdges = 0;
  53. nodeTable = new Vertex<T, E>[maxVertices]; // 创建顶点表数组
  54. if(nodeTable == NULL) {
  55. cerr << "存储空间分配错误!" << endl;
  56. exit(1);
  57. }
  58. for(int i = 0; i < maxVertices; i++)
  59. nodeTable[i].adj = NULL;
  60. }
  61.  
  62. // 析构函数
  63. template <class T, class E>
  64. Graphlnk<T, E>::~Graphlnk() {
  65. // 删除各边链表中的结点
  66. for(int i = 0; i < numVertices; i++) {
  67. Edge<T, E> *p = nodeTable[i].adj; // 找到其对应链表的首结点
  68. while(p != NULL) { // 不断地删除第一个结点
  69. nodeTable[i].adj = p->link;
  70. delete p;
  71. p = nodeTable[i].adj;
  72. }
  73. }
  74. delete []nodeTable; // 删除顶点表数组
  75. }
  76.  
  77. // 建立邻接表表示的图
  78. template <class T, class E>
  79. void Graphlnk<T, E>::inputGraph() {
  80. int n, m; // 存储顶点树和边数
  81. int i, j, k;
  82. T e1, e2; // 顶点
  83. E weight; // 边的权值
  84.  
  85. cout << "请输入顶点数和边数:" << endl;
  86. cin >> n >> m;
  87. cout << "请输入各顶点:" << endl;
  88. for(i = 0; i < n; i++) {
  89. cin >> e1;
  90. insertVertex(e1); // 插入顶点
  91. }
  92.  
  93. cout << "请输入图的各边的信息:" << endl;
  94. i = 0;
  95. while(i < m) {
  96. cin >> e1 >> e2 >> weight;
  97. j = getVertexPos(e1);
  98. k = getVertexPos(e2);
  99. if(j == -1 || k == -1)
  100. cout << "边两端点信息有误,请重新输入!" << endl;
  101. else {
  102. insertEdge(j, k, weight); // 插入边
  103. i++;
  104. }
  105. } // while
  106. }
  107.  
  108. // 输出有向图中的所有顶点和边信息
  109. template <class T, class E>
  110. void Graphlnk<T, E>::outputGraph() {
  111. int n, m, i;
  112. T e1, e2; // 顶点
  113. E weight; // 权值
  114. Edge<T, E> *p;
  115.  
  116. n = numVertices;
  117. m = numEdges;
  118. cout << "图中的顶点数为" << n << ",边数为" << m << endl;
  119. for(i = 0; i < n; i++) {
  120. p = nodeTable[i].adj;
  121. while(p != NULL) {
  122. e1 = getValue(i); // 有向边<i, p->dest>
  123. e2 = getValue(p->dest);
  124. weight = p->cost;
  125. cout << "<" << e1 << ", " << e2 << ", " << weight << ">" << endl;
  126. p = p->link; // 指向下一个邻接顶点
  127. }
  128. }
  129. }
  130.  
  131. // 取位置为i的顶点中的值
  132. template <class T, class E>
  133. T Graphlnk<T, E>::getValue(int i) {
  134. if(i >= 0 && i < numVertices)
  135. return nodeTable[i].data;
  136. return NULL;
  137. }
  138.  
  139. // 返回边(v1, v2)上的权值
  140. template <class T, class E>
  141. E Graphlnk<T, E>::getWeight(int v1, int v2) {
  142. if(v1 != -1 && v2 != -1) {
  143. if(v1 == v2) // 说明是同一顶点
  144. return 0;
  145. Edge<T , E> *p = nodeTable[v1].adj; // v1的第一条关联的边
  146. while(p != NULL && p->dest != v2) { // 寻找邻接顶点v2
  147. p = p->link;
  148. }
  149. if(p != NULL)
  150. return p->cost;
  151. }
  152. return maxValue; // 边(v1, v2)不存在,就存放无穷大的值
  153. }
  154.  
  155. // 插入顶点
  156. template <class T, class E>
  157. bool Graphlnk<T, E>::insertVertex(const T& vertex) {
  158. if(numVertices == maxVertices) // 顶点表满,不能插入
  159. return false;
  160. nodeTable[numVertices].data = vertex; // 插入在表的最后
  161. numVertices++;
  162. return true;
  163. }
  164.  
  165. // 插入边
  166. template <class T, class E>
  167. bool Graphlnk<T, E>::insertEdge(int v1, int v2, E weight) {
  168. if(v1 == v2) // 同一顶点不插入
  169. return false;
  170. if(v1 >= 0 && v1 < numVertices && v2 >= 0 && v2 < numVertices) {
  171. Edge<T, E> *p = nodeTable[v1].adj; // v1对应的边链表头指针
  172. while(p != NULL && p->dest != v2) // 寻找邻接顶点v2
  173. p = p->link;
  174. if(p != NULL) // 已存在该边,不插入
  175. return false;
  176. p = new Edge<T, E>; // 创建新结点
  177. p->dest = v2;
  178. p->cost = weight;
  179. p->link = nodeTable[v1].adj; // 链入v1边链表
  180. nodeTable[v1].adj = p;
  181. numEdges++;
  182. return true;
  183. }
  184. return false;
  185. }
  186.  
  187. // 有向图删除顶点较麻烦
  188. template <class T, class E>
  189. bool Graphlnk<T, E>::removeVertex(int v) {
  190. if(numVertices == 1 || v < 0 || v > numVertices)
  191. return false; // 表空或顶点号超出范围
  192.  
  193. Edge<T, E> *p, *s;
  194. // 1.清除顶点v的边链表结点w 边<v,w>
  195. while(nodeTable[v].adj != NULL) {
  196. p = nodeTable[v].adj;
  197. nodeTable[v].adj = p->link;
  198. delete p;
  199. numEdges--; // 与顶点v相关联的边数减1
  200. } // while结束
  201. // 2.清除<w, v>,与v有关的边
  202. for(int i = 0; i < numVertices; i++) {
  203. if(i != v) { // 不是当前顶点v
  204. s = NULL;
  205. p = nodeTable[i].adj;
  206. while(p != NULL && p->dest != v) {// 在顶点i的链表中找v的顶点
  207. s = p;
  208. p = p->link; // 往后找
  209. }
  210. if(p != NULL) { // 找到了v的结点
  211. if(s == NULL) { // 说明p是nodeTable[i].adj
  212. nodeTable[i].adj = p->link;
  213. } else {
  214. s->link = p->link; // 保存p的下一个顶点信息
  215. }
  216. delete p; // 删除结点p
  217. numEdges--; // 与顶点v相关联的边数减1
  218. }
  219. }
  220. }
  221. numVertices--; // 图的顶点个数减1
  222. nodeTable[v].data = nodeTable[numVertices].data; // 填补,此时numVertices,比原来numVertices小1,所以,这里不需要numVertices-1
  223. nodeTable[v].adj = nodeTable[numVertices].adj;
  224. // 3.要将填补的顶点对应的位置改写
  225. for(int i = 0; i < numVertices; i++) {
  226. p = nodeTable[i].adj;
  227. while(p != NULL && p->dest != numVertices) // 在顶点i的链表中找numVertices的顶点
  228. p = p->link; // 往后找
  229. if(p != NULL) // 找到了numVertices的结点
  230. p->dest = v; // 将邻接顶点numVertices改成v
  231. }
  232. return true;
  233. }
  234.  
  235. // 删除边
  236. template <class T, class E>
  237. bool Graphlnk<T, E>::removeEdge(int v1, int v2) {
  238. if(v1 != -1 && v2 != -1) {
  239. Edge<T, E> * p = nodeTable[v1].adj, *q = NULL;
  240. while(p != NULL && p->dest != v2) { // v1对应边链表中找被删除边
  241. q = p;
  242. p = p->link;
  243. }
  244. if(p != NULL) { // 找到被删除边结点
  245. if(q == NULL) // 删除的结点是边链表的首结点
  246. nodeTable[v1].adj = p->link;
  247. else
  248. q->link = p->link; // 不是,重新链接
  249. delete p;
  250. return true;
  251. }
  252. }
  253. return false; // 没有找到结点
  254. }
  255.  
  256. // 取顶点v的第一个邻接顶点
  257. template <class T, class E>
  258. int Graphlnk<T, E>::getFirstNeighbor(int v) {
  259. if(v != -1) {
  260. Edge<T, E> *p = nodeTable[v].adj; // 对应链表第一个边结点
  261. if(p != NULL) // 存在,返回第一个邻接顶点
  262. return p->dest;
  263. }
  264. return -1; // 第一个邻接顶点不存在
  265. }
  266.  
  267. // 取顶点v的邻接顶点w的下一邻接顶点
  268. template <class T, class E>
  269. int Graphlnk<T, E>::getNextNeighbor(int v,int w) {
  270. if(v != -1) {
  271. Edge<T, E> *p = nodeTable[v].adj; // 对应链表第一个边结点
  272. while(p != NULL && p->dest != w) // 寻找邻接顶点w
  273. p = p->link;
  274. if(p != NULL && p->link != NULL)
  275. return p->link->dest; // 返回下一个邻接顶点
  276. }
  277. return -1; // 下一个邻接顶点不存在
  278. }
  279.  
  280. // 给出顶点vertex在图中的位置
  281. template <class T, class E>
  282. int Graphlnk<T, E>::getVertexPos(const T vertex) {
  283. for(int i = 0; i < numVertices; i++)
  284. if(nodeTable[i].data == vertex)
  285. return i;
  286. return -1;
  287. }
  288.  
  289. // 当前顶点数
  290. template <class T, class E>
  291. int Graphlnk<T, E>::numberOfVertices() {
  292. return numVertices;
  293. }
  294.  
  295. #endif /* Graph_h */

2.Bellman-Ford.h

  1. #ifndef Bellman_Ford_h
  2. #define Bellman_Ford_h
  3. #include "Graph.h"
  4.  
  5. // Bellman-Ford算法
  6. template<class T, class E>
  7. void BellmanFord(Graphlnk<T, E> &G, int v, E dist[], int path[]) {
  8. int i, k, u, n = G.numberOfVertices();
  9. E w;
  10.  
  11. // 1.初始化,将顶点v作为u顶点(存在<v, u>有向边)的上一个顶点,记录路径
  12. for(i = 0; i < n; i++) {
  13. dist[i] = G.getWeight(v, i);
  14. if(i != v && dist[i] < G.maxValue)
  15. path[i] = v;
  16. else
  17. path[i] = -1;
  18. }
  19. // 2.迭代求解:反复对边集E中的每条边进行松弛操作,使得顶点集V中的每个顶点的最短距离估计值逐步逼近其最短距离;(运行n-1次,因为上面算是1次:k=1,所以,k从2开始)
  20. bool isFlag; // 监视该轮dist数组是否有变化
  21. for(k = 2; k < n; k++) {
  22. isFlag = false;
  23. for(u = 0; u < n; u++) { // 遍历顶点,找不是v的顶点
  24. if(u != v) {
  25. for(i = 0; i < n; i++) {
  26. w = G.getWeight(i, u);
  27. if(w != 0 && w < G.maxValue && dist[u] > dist[i] + w) {
  28. // 存在<i, u>边,并且绕过i,使得路径更短,就修改u顶点的最短路径
  29. // w可能是负权值,如果i和u是同一顶点,则w是0,排除同一顶点的情况
  30. // 也可以不写w!=0,因为同一顶点,w=0,dist[u]==dist[i]+w会不满足
  31. // dist[u] > dist[i] + w这个条件
  32. dist[u] = dist[i] + w;
  33. path[u] = i; // 记忆路径
  34. isFlag = true;
  35. }
  36. } // 第3重循环
  37. }
  38. } // 第2重循环
  39. if(isFlag == false) // 如果dist数组没有变化,说明各个顶点已求得最短路径
  40. break;
  41. } // 第1重for循环
  42. }
  43.  
  44. // 从path数组读取最短路径的算法
  45. template <class T, class E>
  46. void printShortestPath(Graphlnk<T, E> &G, int v, E dist[], int path[]) {
  47. int i, j, k, n = G.numberOfVertices();
  48. int *d = new int[n];
  49.  
  50. cout << "从顶点" << G.getValue(v) << "到其他各顶点的最短路径为:" << endl;
  51. for(i = 0; i < n; i++) {
  52. if(i != v) { // 如果不是顶点v
  53. j = i;
  54. k = 0;
  55. while(j != v) {
  56. d[k++] = j;
  57. j = path[j];
  58. }
  59. cout << "顶点" << G.getValue(i) << "的最短路径为:" << G.getValue(v);
  60. while(k > 0)
  61. cout << "->" << G.getValue(d[--k]);
  62. cout << ",最短路径长度为:" << dist[i] << endl;
  63. }
  64. }
  65. }
  66. #endif /* Bellman_Ford_h */

3.main.cpp

  1. /*
  2. 测试数据:
  3. 7 10
  4. 0 1 2 3 4 5 6
  5. 0 1 6
  6. 0 2 5
  7. 0 3 5
  8. 1 4 -1
  9. 2 1 -2
  10. 2 4 1
  11. 3 2 -2
  12. 3 5 -1
  13. 4 6 3
  14. 5 6 3
  15. */
  16.  
  17. #include "Bellman-Ford.h"
  18.  
  19. const int maxSize = 40;
  20.  
  21. int main(int argc, const char * argv[]) {
  22. Graphlnk<char, int> G; // 声明图对象
  23. int dist[maxSize], path[maxSize], v;
  24. char u0;
  25.  
  26. // 创建图
  27. G.inputGraph();
  28. cout << "图的信息如下:" << endl;
  29. G.outputGraph();
  30. cout << "请输入起始顶点u0:" << endl;
  31. cin >> u0;
  32. v = G.getVertexPos(u0); // 取得起始顶点的位置
  33. // 我把dist数组放到有向图头文件中,方便建立有向图时,同时初始化dist数组
  34. BellmanFord(G, v, dist, path); // 调用BellmanFord函数
  35. printShortestPath(G, v, dist, path); // 输出到各个顶点的最短路径
  36. return 0;
  37. }

测试结果:

C++计算任意权值的单源最短路径(Bellman-Ford)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/chuanzhouxiao/article/details/88876704

延伸 · 阅读

精彩推荐