题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1385
解题思路:
题目大意:
有N个城市,然后直接给出这些城市之间的邻接矩阵,矩阵中-1代表那两个城市无道路相连,其他值代表路径长度。
如果一辆汽车经过某个城市,必须要交一定的钱(可能是过路费)。
现在要从a城到b城,花费为路径长度之和,再加上除起点与终点外所有城市的过路费之和。
求最小花费,如果有多条路经符合,则输出字典序最小的路径。
1.这题的关键在于按照字典序输出路径。
假设有
1--->2 2
2--->3 1
1--->3 3
求1到3的最小花费路径.
那么显然后两条路:
1-->3 3
1-->2-->3 3
它们的花费是相同的,但是路径的字典序不同,“123”比“13”字典序要小,所以应当输出1-->2-->3.
用floyd算法打印字典序路径
AC代码:
#include <iostream>
#include <cstdio>
using namespace std;
const int INF = 0xfffffff;
const int N = 105;
int n;
int edge[N][N];
int path[N][N];
int charge[N];
void floyd(){
for(int k = 1; k <= n; k++){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(edge[i][k] != INF && edge[k][j] != INF){
int tmp = edge[i][k]+edge[k][j]+charge[k];
if(edge[i][j] > tmp){
edge[i][j] = tmp;
path[i][j] = path[i][k];
}
else if(edge[i][j] == tmp && path[i][j] > path[i][k])
path[i][j] = path[i][k];
}
}
}
}
}
int main(){
while(scanf("%d",&n),n){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
scanf("%d",&edge[i][j]);
if(edge[i][j] == -1)
edge[i][j] = INF;
path[i][j] = j;
}
}
for(int i = 1; i <= n; i++)
scanf("%d",&charge[i]);
floyd();
int from,to;
while(scanf("%d%d",&from,&to)){
if(from == -1 && to == -1)
break;
printf("From %d to %d :\n",from,to);
printf("Path: ");
int cur = from;
printf("%d",cur);
while(cur != to){
printf("-->%d",path[cur][to]);
cur = path[cur][to];
}
puts("");
printf("Total cost : %d\n\n", edge[from][to]);
}
}
return 0;
}