Input First is N, number of cities. N = 0 indicates the end of input.The data of path cost, city tax, source and destination cities are given in the input, which is of the form:a11 a12 ... a1Na21 a22 ... a2N...............aN1 aN2 ... aNNb1 b2 ... bNc de f...g hwhere aij is the transport cost from city i to city j, aij = -1 indicates there is no direct path between city i and city j. bi represents the tax of passing through city i. And the cargo is to be delivered from city c to city d, city e to city f, ..., and g = h = -1. You must output the sequence of cities passed by and the total cost which is of the form:
Output From c to d :Path: c-->c1-->......-->ck-->dTotal cost : ............From e to f :Path: e-->e1-->..........-->ek-->fTotal cost : ......Note: if there are more minimal paths, output the lexically smallest one. Print a blank line after each test case.
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 分析:典型的floyd(一开始用dijkstra一直RE),这里使用path数组来记录路径,path[a][b]表示a到b的所有路径中的与a最近的一个 结点,path[a][a]则记录当前结点a。另外题目要求按字典序输出结果,只要判断当路径权值相同时,更新结点值小的那个路径即可! 解决了以上两个问题,这就成了水题: 代码如下: #include<cstdio> #include<algorithm> using namespace std; #define INF 0x3f3f3f3f #define read freopen("zx.in","r",stdin) #define write freopen("zx.out","w",stdout) const int N=1000+10; int nnum,cost[N],path[N][N],map[N][N]; //map[a][b]存放a到b的最短路 void floyd() { for(int i=1;i<=nnum;i++) for(int j=1;j<=nnum;j++) path[i][j]=j;//(路径记录)这里记录路径的方法非常不错 for(int k=1;k<=nnum;k++)//floyd算法 for(int i=1;i<=nnum;i++) for(int j=1;j<=nnum;j++) { int temp=map[i][k]+map[k][j]+cost[k];//(+cost[k]一般没有) if(temp<map[i][j]) { map[i][j]=temp, path[i][j]=path[i][k];//记录当前路径 } else if(temp==map[i][j])//如果最短路有多条 { if(path[i][j]>path[i][k]) path[i][j]=path[i][k];//按路径的字典序输出! } }//floyd算法 } int main() { read, write; while(scanf("%d",&nnum)!=EOF && nnum) { for(int i=1;i<=nnum;i++) for(int j=1;j<=nnum;j++) { scanf("%d",&map[i][j]); if(map[i][j]==-1) map[i][j]=INF;//按邻接矩阵输入图 } for(int i=1;i<=nnum;i++) scanf("%d",&cost[i]);//可无 floyd();//进行运算 int a,b;//求解a、b两点之间的最短路 while(scanf("%d%d",&a,&b)!=EOF && a!=-1 && b!=-1) { printf("From %d to %d :/n",a,b); printf("Path: %d",a); int xx=a; while(xx!=b) { printf("-->%d",path[xx][b]); xx=path[xx][b]; } printf("/nTotal cost : %d/n/n",map[a][b]); } } return 0; }