题目大意:以矩阵的形式输入点边关系,-1代表没边,且通过点需要交费,求总花销最小,如果有多种最短路,打印字典序最小的那种
解题思路:floyd,path[i][j]表示i到j的最短路在i之后的最小字典序的点编号,更新的时候加上边相等的时候再更新一下点的字典序
#include <iostream>
#include <cstdio>
using namespace std;
const int INF = 0xfffffff;
const int maxn = 105;
int n;
int edge[maxn][maxn];
int path[maxn][maxn];///path[i][j]表示从i到j的最短路径的i点之后的点
int charge[maxn];
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][j] > edge[i][k]+edge[k][j]+charge[k])
{
edge[i][j] = edge[i][k]+edge[k][j]+charge[k];
path[i][j] = path[i][k];
}
else if(edge[i][j] == edge[i][k]+edge[k][j]+charge[k] && 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;
}