View Code
#include#include #include #include #include #include using namespace std;struct node{ int w,deep,pos,flag;};int pow(int a,int b){ if(b==0)return 1; if(b%2==1)return a*pow(a*a,b/2); else return pow(a*a,b/2);}int min0;bool b[1000001][7][2]={ false};int flag[4]={ 1,6,0,0};int move[4]={ 0,0,1,-1};int swap(int u,int pos1,int pos2){ int temp=u,p1,p2; int t1=pow(10,6-pos1); int t2=pow(10,6-pos2); p1=(u/t1)%10; p2=(u/t2)%10; return temp+(t2-t1)*p1+(t1-t2)*p2;}int getDict(int s,int t,int pos,int flag){ if(s==t)return 0; int sum,mx,mi,t6; t6=sum=0; mx=mi=pos; for(int i=6;i>=1;i--) { int t0=abs(s%10-t%10); s/=10; t/=10; if(t0) { sum+=t0; if(i==6){t6=1;continue;} if(i>mx)mx=i; if(i q1; node in; in.w=s; in.deep=0; in.pos=1; in.flag=0; q1.push(in); b[s][1][0]=true; min0=min(min0,getDict(s,t,1,0)); while(!q1.empty()) { node out=q1.front(); q1.pop(); if(out.deep>=min0)return ; for(int i=0;i<4;i++) { int w=out.w; int pos=out.pos; in.flag=out.flag; if(flag[i]!=0) { w=swap(w,pos,flag[i]); if(flag[i]==6)in.flag=1; } in.pos=pos+move[i]; if(in.pos<1||in.pos>6)continue; if(b[w][in.pos][in.flag])continue; b[w][in.pos][in.flag]=true; in.deep=out.deep+1; min0=min(min0,getDict(w,t,pos,in.flag)+in.deep); in.w=w; q1.push(in); } }}int main(){ int s,t; scanf("%d%d",&s,&t); min0=0x7ffffff; if(s==t){printf("0\n");return 0;} bfs(s,t); printf("%d\n",min0); return 0;}