多段图问题的动态规划算法设计与实现

#include "stdio.h"
#include "conio.h"
#define n  6  /*图的顶点数*/
#define k  4  /*图的段数*/
#define MAX 1000
typedef  int NodeNumber; /*节点编号*/
typedef  int CostType;   /*成本值类型*/
CostType cost[n][n];
NodeNumber path[k];      /*存储最短路径的数组*/
NodeNumber cur= -1;

void creatgraph(CostType *cost[n][n]) /*创建图的成本矩阵*/
{ int i,j;
  printf("请输入图的成本矩阵:/n");
  for(i=0;i<n;i++)
    for(j=0;j<n;j++)
      scanf("%d",&cost[i][j]);
}

void outgraph(CostType *cost[n][n]) /*输出图的成本矩阵*/
{ int i,j;
  printf("输出图的成本矩阵:/n");
  for(i=0;i<n;i++)
   { for(j=0;j<n;j++)
       printf("%d/t",cost[i][j]);
     printf("/n");
   }
}

/* 使用向前递推算法求多段图的最短路径 */
void FPath(CostType *cost[n][n],NodeNumber *path[k])
{ int i,j,length,temp,v[n],d[n];
  for(i=0;i<n;i++) v[i]=0;
  for(i=n-2;i>=0;i--)
    { for(length=MAX,j=i+1;j<=n-1;j++)
        if(cost[i][j]>0 && (cost[i][j])+v[j]<length)
          {length=cost[i][j]+v[j]; temp=j;}
      v[i]=length;
      d[i]=temp;
    }
  path[0]=0;
  path[k-1]=n-1;
  for(i=1;i<=k-2;i++) (path[i])=d[path[i-1]];
}

/* 使用向后递推算法求多段图的最短路径 */
void BPath(CostType *cost[n][n],NodeNumber *path[k])
{ int i,j,length,temp,v[n],d[n];
  for(i=0;i<n;i++) v[i]=0;
  for(i=1;i<=n-1;i++)
    { for(length=MAX,j=i-1;j>=0;j--)
        if(cost[j][i]>0 && (cost[j][i])+v[j]<length)
          {length=cost[j][i]+v[j]; temp=j;}
      v[i]=length;
      d[i]=temp;
    }
  path[0]=0;
  path[k-1]=n-1;
  for(i=k-2;i>=1;i--) (path[i])=d[path[i+1]];
}

/* 查找结点i的后向邻接结点 */
int findbackward(CostType *cost[n][n],NodeNumber i,NodeNumber cur)
{ int j;
  for(j=cur+1;j<n;j++)
    if(cost[i][j]>0) {cur=j;return j;}
    return -1;
}

/* 查找结点i的前向邻接结点 */
int findforward(CostType *cost[n][n],NodeNumber i,NodeNumber cur)
{ int j;
  for(j=cur+1;j<n;j++)
    if(cost[j][i]>0) {cur=j;return j;}
    return -1;
}

/* 输出最短路径序列 */
void outpath(NodeNumber *path[k])
{ int i;
  for(i=0;i<k;i++)
    printf("%d/t",path[i]);
}


main()
{
    NodeNumber m,t;
    creatgraph(&cost);
    outgraph(&cost);
    FPath(&cost,&path);
    printf("输出使用向前递推算法后的最短路径:/n");
    outpath(&path);
    printf("/n输出使用向后递推算法后的最短路径:/n");
    BPath(&cost,&path);
    outpath(&path);
    printf("/n输入要查找邻接结点的编号:");
    scanf("%d",&t);
    printf("结点 %d 的前向邻接结点为: /n");
    cur=findforward(&cost,t,cur);
    while(cur!=-1)   /*找剩下的前向邻接结点*/
      { printf("%d/t",cur);cur=findforward(&cost,t,cur);}
    printf("/n结点 %d 的后向邻接结点为:/n");
    cur=findbackward(&cost,t,cur);
    while(cur!=-1)   /*找剩下的后向邻接结点*/
      { printf("%d/t",cur);cur=findbackward(&cost,t,cur);}
    getch();
}

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值