【BZOJ1054】[HAOI2008]移动玩具【BFS】【Hash】

【题目链接】

大暴搜...hash去重一下就行。

搜到答案时候直接输出是因为BFS时队列前的状态步数是最小的。

/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 7, maxq = 1 << 17, inf = 0x3f3f3f3f;

const int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};

bool vis[maxq];

struct _data {
	bool map[maxn][maxn];
	int step;
} st, ed, q[maxq];

inline bool cread() {
	char ch = getchar();
	for(; ch != '0' && ch != '1'; ch = getchar());
	return ch - '0';
}

inline int hash(_data x) {
	int ans = 0;
	for(int i = 1; i <= 4; i++) for(int j = 1; j <= 4; j++) {
		ans <<= 1;
		ans |= x.map[i][j];
	}
	return ans;
}

int main() {
	for(int i = 1; i <= 4; i++) for(int j = 1; j <= 4; j++) st.map[i][j] = cread(); st.step = 0;
	for(int i = 1; i <= 4; i++) for(int j = 1; j <= 4; j++) ed.map[i][j] = cread();

	int h = 0, t = 0, bg = hash(st), fsh = hash(ed);
	if(bg == fsh) {
		printf("0\n");
		return 0;
	}
	q[t++] = st; vis[bg] = 1;
	while(h != t) {
		_data u = q[h++];
		for(int i = 1; i <= 4; i++) for(int j = 1; j <= 4; j++) if(u.map[i][j]) {
			for(int k = 0; k < 4; k++) {
				int x = i + dx[k], y = j + dy[k];
				if(x < 1 || x > 4 || y < 1 || y > 4 || u.map[x][y]) continue;
				u.map[i][j] = 0; u.map[x][y] = 1;
				int tmp = hash(u);
				if(!vis[tmp]) {
					if(tmp == fsh) {
						printf("%d\n", u.step + 1);
						return 0;
					}
					q[t] = u; q[t].step++; t++;
					vis[tmp] = 1;
				}
				u.map[i][j] = 1; u.map[x][y] = 0;
			}
		}
	}
	return 0;
}


你可能感兴趣的:(【BZOJ1054】[HAOI2008]移动玩具【BFS】【Hash】)