動態規劃法求多段圖的最短路徑
#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++環境下除錯一下可能可以,不過我沒有試過,希望有人試過的話,回個貼。