http://www.lydsy.com/JudgeOnline/problem.php?id=1054
At first, I thought we were going to have a double-search. But very water data, no need.
Direct Bfs+hash weighing can be.
#include <cstdio> #include <cstring> #include <cmath> #include <string> #include <iostream > #include <algorithm>using namespace std; #define REP (i, n) for (int i=0; i< (n); ++i) #define FOR1 (I,a,n) for (in T i= (a); i<= (n) ++i) #define FOR2 (i,a,n) for (int i= (a);i< (n), ++i) #define FOR3 (i,a,n) for (int i= (a); i>= (n);-I.) #define FOR4 (I,a,n) for (int i= (a);i> (n); i) #define CC (i,a) memset (i,a,sizeof (i)) #define READ (a) a=getint () #define Print (a) printf ("%d", a) #define DBG (x) cout << #x << "=" << x << endl#define Printarr (A, N, m) r EP (AAA, N) {rep (BBB, m) cout << a[aaa][bbb]; cout << Endl;} inline const int Getint () {int r=0, k=1; char C=getchar (); for (; c< ' 0 ' | | C> ' 9 '; C=getchar ()) if (c== '-') k=-1; for (; c>= ' 0 ' &&c<= ' 9 '; C=getchar ()) r=r*10+c-' 0 '; return k*r; }inline const int MAX (const int &a, const int &b) {return a>b?a:b;} inline const int min (const int &A, const int &b) {return a<b?a:b; }const int n=1000000, fx[]={-1, 1, 0, 0}, fy[]={0, 0,-1, 1};inline const BOOL Check (const int &x, const int &y) { if (x<0 | | x>3 | | y<0 | | y>3) return 0; return 1; }struct Matrix {bool M[4][4];int D;} Q[n], Ini;int front, tail, ans, vis[100000];inline int hash (const Matrix &x) {int k=1, ret=0;rep (i, 4) Rep (J, 4) {RET +=K*X.M[I][J]; k<<=1; }return ret;} int main () {char c[10];tail=1;rep (i, 4) {scanf ("%s", c), Rep (J, 4) q[0].m[i][j]=c[j]-' 0 ';} Rep (I, 4) {scanf ("%s", c); Rep (J, 4) ini.m[i][j]=c[j]-' 0 ';} int Hs;ans=hash (INI); Hs=hash (q[0]); if (ANS==HS) {printf ("0"); return 0;} Vis[hs]=1;while (front!=tail) {Matrix &x=q[front++]; if (front==n) Front=0;rep (i, 4) Rep (J, 4) if (X.m[i][j]) {rep (k, 4 ) {int px=fx[k]+i, py=fy[k]+j;if (check (px, py) && x.m[px][py]==0) {q[tail]=x; ++q[tail].d;swap (Q[tail].m[i][j] , Q[tail].m[px][py]); Hs=hash (Q[tail]); if (Hs==ans) {printf ("%d", Q[TAIL].D); return 0;} if (VIS[HS]) Continue;vis[hs]=1;++tail; if (tail==n) tail=0;}}}} REturn 0;}
Description
In a 4*4 box placed a number of the same toys, someone want to rearrange these toys into his ideal state, the movement can only move the toys up and down in four directions, and move the position can not have toys, please use the minimum number of moves to move the initial toy state to the target state of someone's heart.
Input
The first 4 lines indicate the initial state of the toy, 4 digits per line 1 or 0, 1 means the toy is placed in the square, and 0 means no toys are placed. Then there is a blank line. The next 4 lines indicate the target state of the toy, 4 digits 1 or 0 per line, with the same meaning.
Output
An integer that requires a minimum number of moves.
Sample Input1111
0000
1110
0010
1010
0101
1010
0101
Sample Output4
Hintsource
"Bzoj" 1054: [HAOI2008] Mobile Toys (Bfs+hash)