您的位置:首页 > 其它

codevs1004(bfs+hash判重)

2016-06-28 18:03 316 查看
本地测试没有问题,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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: