此题最大bug就是一开始的时候INF = 0xfffffff(7个f) 这个数还不够大 INF = 0x3f3f3f3f够大 (0xffffffff(8个f)等于-1)
这道题还有一个特点就是打印路径的时候输出的是字典序最小的那个。如果是cost相同的情况,保存下来的应该是当前字典序最小的那个点。
这道题除了计算路径长度,还有收税,收的是经过的城市的税(起点和终点不收),那么可以假设终点也收,税可以并到路径长度的计算中,只要最后减去终点多收的税就可以了。
#include<cstdio>
#include<cstring>
const int INF = 0x3f3f3f3f;
const int VN = 505;
int main()
{
int n, s, x, y, u, v;
int tax[VN];
int cost[VN][VN], path[VN][VN];
while(~scanf("%d", &n) && n != 0)
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &cost[i][j]);
for (int i = 1; i <= n; i++) scanf("%d", &tax[i]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (cost[i][j] == -1 )
{
cost[i][j] = INF;
path[i][j] = INF; // 因为要求path的最小值,所以要初始化成很大的值
}
else {
cost[i][j] += tax[j];
path[i][j] = j;
}
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (cost[i][k] != INF && cost[k][j] != INF )
{
int tmp = cost[i][k] + cost[k][j];
if (tmp < cost[i][j])
{
cost[i][j] = cost[i][k] + cost[k][j];
path[i][j] = path[i][k];
}
else
if (tmp == cost[i][j] && path[i][k] < path[i][j])
path[i][j] = path[i][k];
}
while (~scanf("%d%d", &x, &y) && !(x == -1 && y == -1))
{
u = x;
v = y;
printf("From %d to %d :\n", x, y);
printf("Path: ");
while (u != v)
{
printf("%d-->", u);
u = path[u][v];
}
printf("%d\n", v);
printf("Total cost : %d\n", cost[x][y]-tax[y]);
printf("\n");
}
}
return 0;
}