Test instructions: It is to restore into 1,2,3,4,5,6,7,8,0;
Analysis: Violent BFS pretreatment, all paths, with comtop expansion weighing, O (1) Print 93ms or very fast.
#include <iostream>#include<cstdio>#include<vector>#include<cstring>#include<algorithm>#include<cmath>#include<queue>using namespacestd;Const intn=5005;intfac[]= {1,1,2,6, -, -,720,5040,40320,362880};intaim;intCantorChars[]) { intans=0; for(intI=1, j=8; i<=9; ++i,--j) {inttmp=0; for(intk=i+1; k<=9; ++k)if(S[i]>s[k]) + +tmp; Ans+ = (tmp*Fac[j]); } returnans;}structnode{Chars[Ten]; intHS;};structasd{BOOLVis; CharC; intPre;} o[362880];queue<Node>Q;voidBFs () {Node A; for(intI=1; i<=8; ++i) a.s[i]='0'+i; a.s[9]='0'; Aim=a.hs=Cantor (A.S); O[aim].vis=1; Q.push (a); while(!Q.empty ()) {a=Q.front (); Q.pop (); intnow=a.hs; intx; for(intI=1; i<=9; ++i)if(a.s[i]=='0') x=i; if(X-3>0) { BOOLflag=0; Swap (A.s[x],a.s[x-3]); A.HS=Cantor (A.S); if(O[A.HS].VIS) flag=1; if(!flag) {O[a.hs].vis=1; O[A.HS].C='D'; O[a.hs].pre=Now ; Q.push (a); } Swap (A.s[x],a.s[x-3]); } if(x+3<Ten) { BOOLflag=0; Swap (A.s[x],a.s[x+3]); A.HS=Cantor (A.S); if(O[A.HS].VIS) flag=1; if(!flag) {O[a.hs].vis=1; O[A.HS].C='u'; O[a.hs].pre=Now ; Q.push (a); } Swap (A.s[x],a.s[x+3]); } if(%3!=1) { BOOLflag=0; Swap (A.s[x],a.s[x-1]); A.HS=Cantor (A.S); if(O[A.HS].VIS) flag=1; if(!flag) {O[a.hs].vis=1; O[A.HS].C='R'; O[a.hs].pre=Now ; Q.push (a); } Swap (A.s[x],a.s[x-1]); } if(%3) { BOOLflag=0; Swap (A.s[x],a.s[x+1]); A.HS=Cantor (A.S); if(O[A.HS].VIS) flag=1; if(!flag) {O[a.hs].vis=1; O[A.HS].C='L'; O[a.hs].pre=Now ; Q.push (a); } Swap (A.s[x],a.s[x+1]); } }}Charstr[ -],tmp[Ten];voidPrintintu) { while(u!=aim) {printf ("%c", O[U].C); U=O[u].pre; } printf ("\ n");}intMain () { for(intI=0;i<326880;++i) O[i].vis=0; BFS (); while(gets (str)) {intL=0; for(intI=0; str[i]!='0'; ++i) {if(str[i]=='x') tmp[++l]='0'; Else if(str[i]>='1'&&str[i]<='9') tmp[++l]=Str[i]; } intans=Cantor (TMP); if(!O[ans].vis) printf ("unsolvable\n"); Elseprint (ANS); } return 0;}
View Code
HDU 1043 Eight BFS