Dijkstra is the most famous Algorithm for short circuit. Therefore, the first response to the question is to use the Dijkstra algorithm. However, this question requires several shortest paths for the start and end points. Therefore, Floyd is the best choice. The other three short-circuit algorithms are single-source.
The template needs to be modified for the path with the smallest output Lexicographic Order.
# Include <iostream> # include <cstdio> # include <cstring> # include <algorithm> using namespace STD; const int n = 110, INF = 1000000; int map [N] [N], DIST [N] [N], pre [N] [N], C [N]; // pre store the int N prior to J in the I to J Path; void Floyd () {int I, j, k; for (I = 1; I <= N; I ++) {for (j = 1; j <= N; j ++) {Dist [I] [J] = map [I] [J]; pre [I] [J] = J ;}for (k = 1; k <= N; k ++) for (I = 1; I <= N; I ++) for (j = 1; j <= N; j ++) {// If (Dist [I] [k] = inf | Dist [k] [J] = inf) continue; int d = DIST [I] [k] + dist [k] [J] + C [k]; If (d <Dist [I] [J]) {Dist [I] [J] = D; Pre [I] [J] = pre [I] [k];} else if (D = DIST [I] [J]) {If (pre [I] [J]> pre [I] [k]) pre [I] [J] = pre [I] [k] ;}} int main () {// freopen ("test.txt", "r", stdin ); int I, J, K, a, B; while (scanf ("% d", & N )! = EOF) {If (! N) break; for (I = 1; I <= N; I ++) for (j = 1; j <= N; j ++) {scanf ("% d", & map [I] [J]); If (Map [I] [J] <0) map [I] [J] = inf ;}for (I = 1; I <= N; I ++) scanf ("% d", & C [I]); while (scanf ("% d", & A, & B) {if (a =-1 & B =-1) break; Floyd (); printf ("from % d to % d: \ n", a, B); printf ("Path: % d", a); k = A; while (K! = B) {printf ("--> % d", pre [k] [B]); k = pre [k] [B];} printf ("\ n"); printf ("Total cost: % d \ n", DIST [a] [B]); printf ("\ n ");}} return 0 ;}
Below is the template of Floyd. Pre [] [] records the precursor. The above record is the successor.
Const int n = 1010, INF = 0x3f3f3f; int map [N] [N], DIST [N] [N], pre [N] [N]; // pre store the int N prior to J in the I to J Path; void Floyd () {int I, j, k; for (I = 1; I <= N; I ++) {for (j = 1; j <= N; j ++) {Dist [I] [J] = map [I] [J]; pre [I] [J] = I ;}for (k = 1; k <= N; k ++) for (I = 1; I <= N; I ++) for (j = 1; j <= N; j ++) if (Dist [I] [k]! = Inf & Dist [k] [J]! = Inf & Dist [I] [k] + dist [k] [J] <Dist [I] [J]) {Dist [I] [J] = DIST [I] [k] + dist [k] [J]; pre [I] [J] = pre [k] [J] ;}} void Init () {for (INT I = 1; I <= N; I ++) for (Int J = 1; j <= N; j ++) map [I] [J] = inf ;}
Hdu1385 minimum transport cost shortest path Floyd with the smallest Lexicographic Order