标签:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 #include <string.h> 6 using namespace std; 7 const int INF = 1 << 25; 8 const int MAX = 1000; 9 int n,path[MAX][MAX],dist[MAX][MAX],tax[MAX]; 10 /path[i][j]用来保存 i --> j 的最短路径中 i 的最优后驱(即最近),在Floyd三重循环时,一直更新path。 11 void Floyd(int n) 12 { 13 for(int i = 1; i <= n; i++) 14 { 15 for(int j = 1; j <= n; j++) 16 path[i][j] = j; 17 } 18 19 for(int k = 1; k <= n; k++) 20 { 21 for(int i = 1; i <= n; i++) 22 { 23 for(int j = 1; j <= n; j++) 24 { 25 if(dist[i][k] < INF && dist[k][j] < INF) 26 { 27 int temp = dist[i][k] + dist[k][j] + tax[k]; 28 if(temp < dist[i][j]) 29 { 30 dist[i][j] = temp; 31 path[i][j] = path[i][k]; 32 } 33 else if(temp == dist[i][j]) //因为是按照字典序输出路径因此当距离相等时,取路径中最小的那个 34 { 35 if(path[i][j] > path[i][k]) 36 path[i][j] = path[i][k]; 37 } 38 } 39 } 40 } 41 } 42 43 44 } 45 int main() 46 { 47 while(scanf("%d", &n) != EOF && n) 48 { 49 for(int i = 1; i <= n; i++) 50 { 51 for(int j = 1; j <= n; j++) 52 { 53 scanf("%d", &dist[i][j]); 54 if(dist[i][j] == -1) 55 dist[i][j] = INF; 56 } 57 } 58 for(int i = 1; i <= n; i++) 59 scanf("%d", &tax[i]); 60 Floyd(n); 61 int start,goal; 62 while(scanf("%d%d", &start,&goal) != EOF) 63 { 64 if(start == -1 && goal == -1) 65 break; 66 printf("From %d to %d :\n",start,goal); 67 68 int temp = start; 69 printf("Path: %d",start); 70 while(temp != goal) 71 { 72 printf("-->%d", path[temp][goal]); 73 temp = path[temp][goal]; 74 } 75 printf("\n"); 76 /* 77 int temp = path[start][goal]; //就是这个一直把start和goal当成不会重复的了,脑子啊~ 78 printf("Path: %d",start); 79 while(temp != goal) 80 { 81 printf("-->%d",temp); 82 temp = path[temp][goal]; 83 } 84 printf("-->%d\n",goal); 85 */ 86 printf("Total cost : %d\n",dist[start][goal]); 87 printf("\n"); 88 } 89 } 90 return 0; 91 }
HD1385Minimum Transport Cost(Floyd + 输出路径)
标签:
原文地址:http://www.cnblogs.com/zhaopAC/p/4990040.html