bzoj1054: [HAOI2008]移动玩具

题目

题解:

题目很简单,二进制压缩成16位,然后bfs就好,但是有两个坑点,需要注意一下。
1.bfs时搜索i-1,i+1时,目的是搜索左边那列和右边那列,但是当i%4==0或i%4==3时会到上一行或者下一行
2.对于一些做法,目标状态与起始状态相等时会有错误

标程:

#include<bits/stdc++.h>
using namespace std;
int i,j,x,y,h,t,q[1<<16],dis[1<<16],tmp,v,u,fl;
char s[5];
void pd(int x){
    if (!(tmp&(1<<x)) && !dis[v=(tmp|(1<<x))]) q[t++]=v,dis[v]=dis[u]+1;
}
int main(){
    for (i=0;i<4;i++){
        scanf("%s",s);
        for (j=0;j<4;j++) x=(x<<1)|(s[j]^48);
    }
    for (i=0;i<4;i++){
        scanf("%s",s);
        for (j=0;j<4;j++) y=(y<<1)|(s[j]^48);
    }
    h=0;t=1;q[0]=x;dis[x]=1;
    while (h<t){
        u=q[h++];
        for (i=0;i<16;i++)
            if (u&(1<<i)){
                tmp=u^(1<<i);
                if (i&3) pd(i-1);
                if ((i&3)<3) pd(i+1);
                if (i>3) pd(i-4);
                if (i<12) pd(i+4);
                if (dis[y]){
                    printf("%d",dis[y]-1);
                    return 0;
                }
            }
    }
}

猜你喜欢

转载自blog.csdn.net/xumingyang0/article/details/80925272