codevs1004(bfs+hash判重)

本地测试没有问题,codevs却和本地测的结果不一样,可能是编译环境不同吧!

然后为了判断我的程序是否正确,找了题解来对拍,多了一会,停了。。。。然而最后发现题解竟然错了。。。。(codevs数据真弱。。。)

换了几个对拍后,确定没有问题


updata 2016.11.5


#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<algorithm>
using namespace std;
const int mod=9999991;
const int qx[]={0,0,1,-1};
const int qy[]={1,-1,0,0};

struct aa
{
	int x,y,xx,yy,step;
	bool o;
	int a[5][5];
}st;
bool hs[10000001];
int get_hs(aa &a)
{
	int x=0,y;
	for (int i=1;i<=4;i++)
	{
		y=0;
		for (int j=1;j<=4;j++) y=y*3+a.a[i][j];
		x=(x*91%mod+y)%mod;//行列p值不能重复
	}
	return x;
}

bool ok(aa &a,int x,int y)
{
	if (x<1||x>4||y<1||y>4||a.a[x][y]==0) return false;
	return true;
}
bool pan(aa &a)
{
	bool o;
	for (int i=1;i<=4;i++)
	{
		o=true;
		for (int j=2;j<=4;j++) if (a.a[i][j]!=a.a[i][j-1]) o=false;
		if (o) return true;
		o=true;
		for (int j=2;j<=4;j++) if (a.a[j][i]!=a.a[j-1][i]) o=false;
		if (o) return true; 
	}
	o=true;
	for (int i=2;i<=4;i++) if (a.a[i][i]!=a.a[i-1][i-1]) o=false;if (o) return true;
	o=true;
	for (int i=2;i<=4;i++) if (a.a[i][4-i+1]!=a.a[i-1][4-i+2])o=false; if (o) return true;
	return false; 
}

int main()
{
	char s[6];
	for (int i=1;i<=4;i++) 
	{
		scanf("%s",s+1);
		for (int j=1;j<=4;j++) 
		{
			if (s[j]=='W') {st.a[i][j]=1;continue;}
			if (s[j]=='B') {st.a[i][j]=2;continue;} 
			if (st.x==0)
			st.x=i,st.y=j;
			else 
			st.xx=i,st.yy=j;
		}
	}
	
	queue<aa> q;
	
	
	int ans=0,sx,sy,tx,ty,h;
	if (pan(st)){printf("0");return 0;}
	h=get_hs(st);
	hs[h]=true;
	
	
	
	for (int i=0;i<=1;i++)
	{
		if (i==0) sx=st.x,sy=st.y;
		else sx=st.xx,sy=st.yy;
		for (int j=0;j<4;j++) if (ok(st,sx+qx[j],sy+qy[j]))
		{
			tx=sx+qx[j],ty=sy+qy[j];
			aa b=st;
			swap(b.a[sx][sy],b.a[tx][ty]);
			if (b.a[sx][sy]==1) b.o=false;else b.o=true;
			if (pan(b)) {printf("1");return 0;}
			h=get_hs(b);hs[h]=true;b.step=1;
			if (i==0) b.x=tx,b.y=ty;else b.xx=tx,b.yy=ty;
			q.push(b);
		}
	}
	
	
	
	while (!q.empty())
	{
		aa u=q.front();q.pop();
		for (int i=0;i<=1;i++)xjr//代码技巧,减少二分之一长度
		{
			if (i==0) sx=u.x,sy=u.y;
			else sx=u.xx,sy=u.yy;
			for (int j=0;j<4;j++) if (ok(u,sx+qx[j],sy+qy[j]))
			{
				tx=sx+qx[j],ty=sy+qy[j];
				if ((u.a[tx][ty]==1&&u.o==false)||(u.a[tx][ty]==2&&u.o==true)) continue;
				aa b=u;
				swap(b.a[sx][sy],b.a[tx][ty]);
				if (hs[h=get_hs(b)]) continue;hs[h]=true;
				b.step=u.step+1;b.o=!b.o;
				if (pan(b)) {printf("%d",b.step);return 0;}
				if (i==0) b.x=tx,b.y=ty;else b.xx=tx,b.yy=ty;
				q.push(b);
			}
		}
	}
	
	return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值