【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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值