hdu 1385 Floyd 输出路径

Floyd 输出路径

Sample Input
5
0 3 22 -1 4
3 0 5 -1 -1
22 5 0 9 20
-1 -1 9 0 4
4 -1 20 4 0
5 17 8 3 1 //收费
1 3 //起点 终点
3 5
2 4
-1 -1
0

Sample Output
From 1 to 3 :
Path: 1-->5-->4-->3
Total cost : 21

From 3 to 5 :
Path: 3-->4-->5
Total cost : 16

From 2 to 4 :
Path: 2-->1-->5-->4
Total cost : 17

 1 # include <iostream>
 2 # include <cstdio>
 3 # include <cstring>
 4 # include <string>
 5 # include <algorithm>
 6 # include <cmath>
 7 # include <map>
 8 # define LL long long
 9 using namespace std ;
10 
11 const int MAXN = 310 ;
12 const int INF = 0x3f3f3f3f;
13 int dis[MAXN][MAXN];
14 int b[MAXN] ;
15 int path[MAXN][MAXN] ;
16 int n ;
17 
18 void floyed()//节点从1~n编号
19 {
20     int i,j,k;
21     for (i = 1; i <= n; i++)
22         for (j = 1; j <= n; j++)
23             path[i][j] = j;  //记录路径数组初始化,表示从i到j经过的第一个站
24     for(k=1;k<=n;k++)
25        for(i=1;i<=n;i++)
26          for(j=1;j<=n;j++)
27          {
28              int t = dis[i][k]+dis[k][j] + b[k] ;
29              if (t < dis[i][j])
30              {
31                  dis[i][j] = t ;
32                  path[i][j] = path[i][k] ;
33              }
34              else if (t == dis[i][j] && path[i][k] < path[i][j])
35                  path[i][j] = path[i][k] ;
36 
37          }
38 
39 
40 }
41 
42 int main()
43 {
44    // freopen("in.txt","r",stdin) ;
45     while (scanf("%d" , &n) , n)
46     {
47         int i , j ;
48         for (i = 1 ; i <= n ; i++)
49             for (j = 1 ; j <= n ; j++)
50         {
51             scanf("%d" , &dis[i][j]) ;
52             if (dis[i][j] == -1)
53                 dis[i][j] = INF ;
54         }
55         for (i = 1 ; i <= n ; i++)
56             scanf("%d" , &b[i]) ;
57         floyed() ;
58         int u , v ;
59         while(scanf("%d %d" , &u , &v) )
60         {
61             if (u == -1 && v == -1)
62                 break ;
63             printf ("From %d to %d :
", u, v);
64             printf ("Path: %d", u);
65             int t = u;
66             while (u != v)
67             {
68                 printf ("-->%d", path[u][v]);
69                 u = path[u][v];
70             }
71             printf ("
Total cost : %d

", dis[t][v]);
72         }
73 
74     }
75     return 0;
76 }
View Code
原文地址:https://www.cnblogs.com/mengchunchen/p/4590779.html