当前位置:   article > 正文

多段图的最短路径 图问题中的动态规划法(C++实现)_动态规范算法实现多段图的最短路径问题

动态规范算法实现多段图的最短路径问题

问题:设图G=(V,E)是一个带权有向图多段图的最短路径问题(Multi-segment Graph Shortest Path Problem)求从源点到终点的最小代价路径。

算法:设置cost数组记载当前从原点到该点的最短路径,path数组记录最短路径当前点的前驱。

代码如下:

  1. int ShortestPath(int arc[100][100],int n){
  2. int i,j,cost[n],path[n];
  3. cost[0] = 0;path[0] = -1;//顶点0为原点,初始化
  4. for(j=1;j<n;j++){
  5. cost[j] = 100;//默认单路径长度不大于100
  6. for(i=0;i<j;i++){
  7. if(arc[i][j] > 0){//如果从i到j的边存在
  8. if(cost[i] + arc[i][j] < cost[j]){//从原点到i的cost加上ij边,与原点到j的边比较
  9. cost[j] = cost[i] + arc[i][j];//取路径小的
  10. path[j] = i;//j的前驱是i
  11. }
  12. }
  13. }
  14. }
  15. cout<<--n;//最后一个点
  16. for(i=n;path[i]>=0;){
  17. cout<<"<--"<<path[i];
  18. i = path[i];
  19. }
  20. cout<<endl;
  21. return cost[n];//返回最短路径长度
  22. }

构建图:

  1. struct Graph{
  2. int Vex[100];//顶点
  3. int arc[100][100];//边的权
  4. int vexnum,arcnum;//顶点数、边数
  5. };
  6. void InitGraph(Graph &G){
  7. G.vexnum = G.arcnum = 0;
  8. }
  9. void InsertVex(Graph &G,int v){
  10. G.Vex[G.vexnum++] = v;
  11. }
  12. int LocateVex(Graph &G,int v){
  13. for(int i=0;i<=G.vexnum;i++)
  14. if(v == G.Vex[i]) return i;
  15. return -1;
  16. }
  17. void InsertEdge(Graph &G,int v1,int v2,int e){
  18. int v1num = LocateVex(G,v1);
  19. int v2num = LocateVex(G,v2);
  20. G.arc[v1num][v2num] = e;
  21. G.arcnum += 1;
  22. }
  23. void ShowGraph(Graph &G){
  24. cout<<"代价矩阵:"<<endl;
  25. cout<<" ";
  26. for(int i=0;i<G.vexnum;i++)
  27. cout<<G.Vex[i]<<" ";
  28. cout<<endl;
  29. for(int i=0;i<G.vexnum;i++){
  30. cout<<G.Vex[i]<<" ";
  31. for(int j=0;j<G.vexnum;j++) cout<<G.arc[i][j]<<" ";
  32. cout<<endl;
  33. }
  34. cout<<endl;
  35. }

测试如下:

  1. int main(){
  2. Graph G;
  3. InitGraph(G);
  4. InsertVex(G,0);InsertVex(G,1);InsertVex(G,2);InsertVex(G,3);InsertVex(G,4);
  5. InsertVex(G,5);InsertVex(G,6);InsertVex(G,7);InsertVex(G,8);InsertVex(G,9);
  6. InsertEdge(G,0,1,4);InsertEdge(G,0,2,2);InsertEdge(G,0,3,3);
  7. InsertEdge(G,1,4,9);InsertEdge(G,1,5,8);InsertEdge(G,2,4,6);
  8. InsertEdge(G,2,5,7);InsertEdge(G,2,6,8);InsertEdge(G,3,5,4);
  9. InsertEdge(G,3,6,7);InsertEdge(G,4,7,5);InsertEdge(G,4,8,6);
  10. InsertEdge(G,5,7,8);InsertEdge(G,5,8,6);InsertEdge(G,6,7,6);
  11. InsertEdge(G,6,8,5);InsertEdge(G,7,9,7);InsertEdge(G,8,9,3);
  12. ShowGraph(G);
  13. int cost = ShortestPath(G.arc,10);
  14. cout<<"最短路径长度为:"<<cost<<endl;
  15. }

输出如下:

代价矩阵:
   0  1  2  3  4  5  6  7  8  9
0  0  4  2  3  0  0  0  0  0  0
1  0  0  0  0  9  8  0  0  0  0
2  0  0  0  0  6  7  8  0  0  0
3  0  0  0  0  0  4  7  0  0  0
4  0  0  0  0  0  0  0  5  6  0
5  0  0  0  0  0  0  0  8  6  0
6  0  0  0  0  0  0  0  6  5  0
7  0  0  0  0  0  0  0  0  0  7
8  0  0  0  0  0  0  0  0  0  3
9  0  0  0  0  0  0  0  0  0  0

9<--8<--5<--3<--0
最短路径长度为:16

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/831225
推荐阅读
相关标签
  

闽ICP备14008679号