代碼:
#include<bits/stdc++.h>
using namespace std;
int arc[20][20];
const int MAX = 1000; // 假定邊上的權值均不超過1000
int CreateGraph()
{
int i,j,k;
int weight;
int vnum,arcnum;
cout<<"請輸入頂點的個數和邊的個數:";
cin>>vnum>>arcnum;
// 初始化圖的代價矩陣
for(i=0; i<vnum; i++)
for(j=0; j<vnum; j++)
arc[i][j]=MAX;
// 建立圖的代價矩陣
for(k=0; k<arcnum; k++)
{
cout<<"請輸入邊的兩個頂點和權值:"<<endl;
cin>>i>>j>>weight;
arc[i][j]=weight;
}
return vnum; // 返回頂點個數
}
// 求n個頂點長度多段圖的最短路徑
int BackPath(int n)
{
int i,j;
int cost[n],path[n]; // 存儲路徑長度和路徑
for(i=1; i<n; i++)
{
cost[i]=MAX; // 初始化路徑長度爲MAX
path[i]=-1;
}
cost[0]=0; // 頂點0爲源點
path[0]=-1;
// 執行填表工作
for(j=1; j<n; j++)
{
// 考察所有入邊
for(i=j-1; i>=0; i--)
{
if(arc[i][j]+cost[i]<cost[j])
{
cost[j]=arc[i][j]+cost[i];
path[j]=i;
}
}
}
cout<<n-1; // 輸出終點
i=n-1;
while(path[i]>=0) // 依次輸出path[i]
{
cout<<"<-"<<path[i];
i=path[i]; // 求得路徑上頂點i的前一個頂點
}
cout<<endl;
return cost[n-1]; // 返回最短路徑長度
}
int main()
{
int n,m;
n=CreateGraph();
m=BackPath(n);
cout<<m<<endl;
return 0;
}
測試數據:
10 18
0 1 4
0 2 2
0 3 3
1 4 9
1 5 8
2 4 6
2 5 7
2 6 8
3 5 4
3 6 7
4 7 5
4 8 6
5 7 8
5 8 6
6 7 6
6 8 5
7 9 7
8 9 3
輸出: