BZOJ1054(搜索)

大力搜,状态用一个16位的数字表示。


#include <bits/stdc++.h>

using namespace std;

#define rep(i,a,b)              for(int i(a); i <= (b); ++i)

const int A     =    30          +       1;

struct node{int x, y; } op[A];
struct Node{int num, step;} now, np;

char st[A][A];
int f[A][A];
int h[1 << 18];
int x, y, nx, ny, s, t, cnt = 0;

queue <Node> Q;

int main(){

	rep(i, 1, 8) scanf("%s", st[i] + 1);
	cnt = 0;
	rep(i, 1, 4) rep(j, 1, 4) f[i][j] = cnt++;
	rep(i, 5, 8) rep(j, 1, 4) f[i][j] = f[i - 4][j];
	
	s = 0, t = 0;

	rep(i, 1, 4) rep(j, 1, 4) if (st[i][j] == '1') s |= (1 << f[i][j]);
	rep(i, 5, 8) rep(j, 1, 4) if (st[i][j] == '1') t |= (1 << f[i][j]);

	cnt = 0;

	rep(i, 1, 3) rep(j, 1, 4){ op[++cnt].x = f[i][j], op[cnt].y = f[i + 1][j];}
	rep(i, 1, 4) rep(j, 1, 3){ op[++cnt].x = f[i][j], op[cnt].y = f[i][j + 1];}

	memset(h, 0, sizeof h); h[s] = 1; Q.push({s, 0});
	
	while (!Q.empty()){
		np = Q.front(); Q.pop();
		if (np.num == t){
			printf("%d\n", np.step);
			break;
		}
		rep(i, 1, cnt){
			now = np;
			x = op[i].x, y = op[i].y;
			nx = (now.num >> x) & 1, ny = (now.num >> y) & 1;
			if (nx ^ ny){
				now.num ^= (1 << x);
				now.num ^= (1 << y);
			}

			if (!h[now.num]){
				h[now.num] = 1;
				Q.push({now.num, now.step + 1});
			}
		}
	}

	return 0;

}




posted @ 2017-01-13 10:01  cxhscst2  阅读(167)  评论(0编辑  收藏  举报