使用DP的思想:考虑从i到j的最短路径经过K一次和完全不经过K两种情况来讨论:
DP[i][j]=min(dp[i][j],dp[i][k]+dp[k][j])
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
const int maxv=100;
const int INF=999999;
int weight[maxv][maxv];
int n,m; // n个顶点,编号为1,2,3...n,m条边
void floyd_warshall()
{
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
weight[i][j]=min(weight[i][j],weight[i][k]+weight[k][j]);
}
}
}
}
int main()
{
while(cin>>n>>m)
{
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j)weight[i][j]==0;
else weight[i][j]=INF;
}
}
for(int i=0;i<m;i++)
{
int u,v,cost;
cin>>u>>v>>cost;
weight[u][v]=cost;
}
floyd_warshall();
for(int i=1;i<=n;i++)
cout<<weight[1][i]<<" ";
cout<<endl;
}
}
给出一组测试实例 DAG:
5 7
1 2 10
1 5 100
1 4 30
2 3 50
3 5 10
4 3 20
4 5 60
其中从顶点1 到其余所有顶点的最短路径为:
0 10 50 30 60