1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
| #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cctype> #include <queue> #include <utility> #include <cmath> #include <map> #define ll long long #define ri register int #define ull unsigned long long using namespace std; template <class T>inline void read(T &x){ x=0;int ne=0;char c; while(!isdigit(c=getchar()))ne=c=='-'; x=c-48; while(isdigit(c=getchar()))x=(x<<3)+(x<<1)+c-48; x=ne?-x:x;return ; } const int maxn=5; const int inf=0x7fffffff; const int dx[4]={-1,0,0,1},dy[4]={0,-1,1,0}; const char ch[4]={'u','l','r','d'}; int sta[maxn][maxn]; ll st,goal; map <ll,ll> pre; map <ll,int> dir; pair<int,int>pos[10]; struct Sta{ ll a; int s,f; Sta(){;} Sta(ll _a,int _s,int _f){a=_a,s=_s,f=_f;} bool operator <(const Sta &b)const{ return f>b.f; } }; int bx,by; inline int get_f(){ int ans=0; for(ri i=1;i<=3;i++){ for(ri j=1;j<=3;j++){ if(sta[i][j]==0)continue; ans+=abs(i-pos[sta[i][j]].first)+abs(j-pos[sta[i][j]].second); } } return ans; } inline ll turn_num(){ ll ans=0; for(ri i=1;i<=3;i++){ for(ri j=1;j<=3;j++){ ans=ans*10+sta[i][j]; } } return ans; } inline void turn_sta(ll num){ for(ri i=3;i>=1;i--){ for(ri j=3;j>=1;j--){ sta[i][j]=num%10; num=num/10; if(!sta[i][j])bx=i,by=j; } } return ; } void print(ll x){ if(x==st)return ; print(pre[x]); putchar(ch[dir[x]]); return ; } inline void astar(){ ll now,nxt; int x,y,z; Sta tmp; priority_queue<Sta>q; while(q.size())q.pop(); turn_sta(st); q.push(Sta(st,0,get_f())); while(q.size()){ tmp=q.top();q.pop(); now=tmp.a,z=tmp.s; if(now==goal){ print(goal); return ; } turn_sta(now); for(ri i=0;i<4;i++){ x=bx+dx[i],y=by+dy[i]; if(x>=1&&x<=3&&y>=1&&y<=3){ swap(sta[bx][by],sta[x][y]); nxt=turn_num(); if(!pre[nxt]){ pre[nxt]=now; dir[nxt]=i; q.push(Sta(nxt,z+1,z+1+get_f())); } swap(sta[bx][by],sta[x][y]); } } } puts("unsolvable"); return ; } int main(){ int num[10]; char x[2]; pos[0].first=3,pos[0].second=3; pos[1].first=1,pos[1].second=1; pos[2].first=1,pos[2].second=2; pos[3].first=1,pos[3].second=3; pos[4].first=2,pos[4].second=1; pos[5].first=2,pos[5].second=2; pos[6].first=2,pos[6].second=3; pos[7].first=3,pos[7].second=1; pos[8].first=3,pos[8].second=2; st=0; for(ri i=1;i<=9;i++){ scanf("%s",x); if(x[0]=='x')st=st*10,num[i]=inf; else st=st*10+x[0]-'0',num[i]=x[0]-'0'; } int cnt=0; for(ri i=1;i<=9;i++){ if(num[i]==inf)continue; for(ri j=i+1;j<=9;j++){ if(num[j]<num[i]){cnt++;} } } if(cnt%2==1){ puts("unsolvable"); } else{ pre[st]=19260817; goal=123456780; astar(); } return 0; }
|