动态规划法求多段图的最短路径

#include "stdio.h"
#include "conio.h"
#define n 16 /*图的顶点数*/
#define k 7  /*图的段数*/
#define l 30
#define MAX 100
typedef int NodeNumber;/*节点编号*/
typedef int CostType;/*成本值类型*/
CostType cost[n][n];
NodeNumber path[k];
NodeNumber cur=-1;
void creategraph(CostType *cost[n][n]) /*创建图的成本矩阵*/
{
  int i,j,x,y,value;
  for(i=0;i<n;i++)
    for(j=0;j<n;j++)  cost[i][j]=0;
  printf("/nEnter the cost of graph:/n");
  for(i=0;i<l;i++)
  {
    scanf("%d,%d,%d",&x,&y,&value);
    cost[x][y]=value;
  }
}
void outgraph(CostType *cost[n][n]) /*输出图的成本矩阵*/
{
  int i,j;
  printf("Print the cost of graph:/n");
  for(i=0;i<n;i++)
  {
    for(j=0;j<n;j++)  printf("%2d",cost[i][j]);
    printf("/n");
  }
}
/*使用向前递推算法求多段图的最短路径*/
void FPath(CostType *cost[n][n],NodeNumber *path[k])
{
  int i,j,leng,temp,v[n],d[n];
  for(i=0;i<n;i++) v[i]=0;
  for(i=n-2;i>=0;i--)
  { leng=MAX;
    for(j=i+1;j<=n-1;j++)
    if(cost[i][j]>0  && (cost[i][j]+v[j])<leng)
    {
      leng=cost[i][j]+v[j];temp=j;
    }
    v[i]=leng;
    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 outpath(NodeNumber *path[k])
{
  int i;
  printf("/nPrint the shortest treet:/n");
  for(i=0;i<k;i++)  printf("%3d",path[i]);
}
main()
{
  NodeNumber m,t;
  creategraph(&cost);
  outgraph(&cost);
  FPath(&cost,&path);
  outpath(&path);
}

这个程序可以运行, 不过这里有一个问题:

就是当我输入小的多段图的时候(如10个顶点,5个分段,18个权值即18条线),可以得到正确的答案,但

是输入太大的多段图的时候(如16个顶点,7个分段,30个权值),就得不到正确的答案。我老师说可能是

内存问题,叫我到C++环境下调试一下可能可以,不过我没有试过,希望有人试过的话,回个贴。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值