Minimum Transport Cost
The meaning of the question is very simple. There are n cities, and the distance between them is given using an adjacent matrix. The key problem lies in finding the shortest path and outputting the smallest Lexicographic Order. I never thought about this problem before, and never thought about how to output the shortest one. In fact, it is not very simple, that is, use Floyd to obtain the point-to-distance, and use the shortest distance as a strong pruning in the lexicographically ordered DFS, the first valid path is the shortest and minimum lexicographic path. The path output can be implemented recursively.
Code
# Include < Stdio. h >
# Include < String . H >
# Define INF 0 xfffffff
# Define Nn 100
Int N, S, T, OK;
Int Dis [NN] [NN];
Int Map [NN] [NN];
Int Mark [NN];
Int Pre [NN];
Int Cost [NN];
Void Floyd (){
Int I, J, K;
Memcpy (DIS, map, Sizeof (MAP ));
For (K = 1 ; K <= N; k ++ ){
For (I = 1 ; I <= N; I ++ ){
For (J = 1 ; J <= N; j ++ ){
If (DIS [I] [J] > Dis [I] [k] + Dis [k] [J] + Cost [k]) {
Dis [I] [J] = Dis [I] [k] + Dis [k] [J] + Cost [k];
}
}
}
}
}
Void DFS ( Int Cur, Int D ){
Int I, T;
If (D > Dis [s] [T]) Return ;
If (Cur = T && D = Dis [s] [T]) {
OK = 1 ;
Return ;
}
For (I = 1 ; I <= N; I ++ ){
If ( ! Mark [I]) {
Mark [I] = 1 ;
Pre [I] = Cur;
T = D + Map [cur] [I];
If (I ! = T ){
T + = Cost [I];
}
DFS (I, T );
If (OK) Return ;
Mark [I] = 0 ;
}
}
}
Void Out ( Int Cur ){
If (Cur = S ){
Printf ( " % D " , Cur );
Return ;
}
Out (Pre [cur]);
Printf ( " --> % D " , Cur );
}
Int Main ()
{
Int I, j, A, B;
// Freopen ("q1456.in", "r", stdin );
// Freopen ("A. Out", "W", stdout );
While (Scanf ( " % D " , & N) ! = EOF ){
If (N = 0 ) Break ;
For (I = 1 ; I <= N; I ++ ){
For (J = 1 ; J <= N; j ++ ){
Scanf ( " % D " , & A );
If ( = - 1 ) = INF;
Map [I] [J] = A;
}
}
For (I = 1 ; I <= N; I ++ ){
Scanf ( " % D " , & Cost [I]);
}
Floyd ();
While (Scanf ( " % D " , & A, & B) ! = EOF ){
If ( = - 1 && B = - 1 ) Break ;
S = A;
T = B;
OK = 0 ;
Memset (mark, 0 , Sizeof (Mark ));
DFS (S, 0 );
Printf ( " From % d to % d: \ npath: " , A, B );
Out (B); puts ( "" );
Printf ( " Total cost: % d \ n " , DIS [a] [B]);
Puts ( "" );
}
}
Return 0 ;
}