This question can be viewed as a result of the brute-force BFS attack and timeout. It is only available when you look at Daniel's blog .. For one state to another, it can be converted to 12345678 to another State. In this case, you only need to replace it. In this way, only one BFS preprocessing can process all the situations .. You do not need to search every case...
# Include <cstdio> # include <queue> # include <map> # include <string> # include <algorithm> # include <iostream> using namespace STD; struct node {string STR; string step; int va ;}; string S, T; int VI [50000]; string DP [50000]; int POS [10]; int func [10]; int Hash (string & S) {int Va = 0; For (INT I = 0; I <7; I ++) {int CNT = 0; for (Int J = I + 1; j <8; j ++) if (s [J] <s [I]) CNT ++; va + = CNT * func [7-i];} return Va;} void gao1 (string & S) {for (INT I = 0; I <4; I ++) S WAP (s [I], s [I + 4]);} void gao2 (string & S) {char T = s [3]; for (INT I = 2; i> = 0; I --) s [I + 1] = s [I]; s [0] = T; t = s [7]; for (INT I = 6; I> = 4; I --) s [I + 1] = s [I]; s [4] = T ;} void gao3 (string & S) {char TP = s [1]; s [1] = s [5]; s [5] = s [6]; s [6] = s [2]; s [2] = TP;} void BFS () {memset (Vi, 0, sizeof (VI )); queue <node> q; node SS, TT; SS. STR = s; SS. step = ""; SS. va = hash (s); q. push (SS); VI [ss. VA] = 1; DP [ss. VA] = ""; while (! Q. empty () {Ss = Q. front (); q. pop (); string T = ss. STR; int K; gao1 (t); k = hash (t); If (! VI [k]) {TT. STR = T; VI [k] = 1; TT. step = ss. step + 'a'; TT. va = K; DP [k] = TT. step; q. push (TT);} t = ss. STR; gao2 (t); k = hash (t); If (! VI [k]) {TT. STR = T; VI [k] = 1; TT. step = ss. step + 'B'; TT. va = K; DP [k] = TT. step; q. push (TT);} t = ss. STR; gao3 (t); k = hash (t); If (! VI [k]) {TT. STR = T; VI [k] = 1; TT. step = ss. step + 'C'; TT. va = K; DP [k] = TT. step; q. push (TT) ;}}int main () {func [0] = 1; for (INT I = 1; I <= 9; I ++) func [I] = func [I-1] * I; S = "12345678"; BFS (); While (CIN> S> T) {swap (s [4], s [7]); swap (s [5], s [6]); swap (T [4], t [7]); swap (T [5], T [6]); For (INT I = 0; I <8; I ++) POS [s [I]-'0'] = I + 1; for (INT I = 0; I <8; I ++) T [I] = POS [T [I]-'0']; /* replace */int K = hash (t); cout <DP [k] <Endl;} return 0 ;}