bfs+hash判重 为何只有50 求指教

#include<map>
#include<cstdio>
#include<iostream>
#define MAXN 400010

using namespace std;

struct node {
    int a[4][4];
    bool operator < (const node &other) const {
        for(int i=0; i<4; i++)
            for(int j=0; j<4; j++) {
                if(a[i][j]<other.a[i][j])
                    return true;
                if(a[i][j]>other.a[i][j])
                    return false;
            }
        return false;
    }
};
node e[MAXN];

int mp[4][4];

int step[MAXN],head,tail;

int x[4]= {0,1,0,-1};
int y[4]= {1,0,-1,0};

char s[110];

bool flag,_HASH[1300000];

map<node,int> m;

inline bool pd(int xx,int yy) {
    if(xx<0||yy<0) return false;
    if(xx>4||yy>4) return false;
    else return true;
}

inline bool check() {
    for(int i=0; i<4; i++)
        for(int j=0; j<4; j++)
            if(mp[i][j]!=e[tail].a[i][j]) return false;
    return true;
}

inline bool _hash() {
    int now=0;
    for(int i=0;i<4;i++)
      for(int j=0;j<4;j++) {
        now<<=1;
        now+=e[tail].a[i][j];
      }
    if(_HASH[now]) return false;
    _HASH[now]=true;
    return true; 
}

inline void search() {
    while(head<tail) {
        for(int xx=0; xx<4; xx++)
            for(int yy=0; yy<4; yy++) 
                for(int i=0; i<4; i++) {
                    int _x=xx+x[i];
                    int _y=yy+y[i];
                    if(pd(_x,_y)) {
                        for(int i=0; i<4; i++)
                            for(int j=0; j<4; j++)
                                e[tail].a[i][j]=e[head].a[i][j];
                        step[tail]=step[head]+1;
                        swap(e[tail].a[_x][_y],e[tail].a[xx][yy]);
                        if(check()) {
                            printf("%d\n",step[tail]);
                            return;
                        }
                        if(_hash()) tail++;
                    }
                }
        head++;
    }
}

int main() {
    for(int i=0; i<4; i++) {
        scanf("%s",s);
        for(int j=0; j<4; j++)
            if(s[j]=='1')
                mp[i][j]=1;
    }
    getchar();
    for(int i=0; i<4; i++) {
        scanf("%s",s);
        for(int j=0; j<4; j++)
            if(s[j]=='1')
                e[0].a[i][j]=1;
    }
    if(check()) {
        printf("0\n");
        return 0;
    }
    tail=1;
    search();
    return 0;
}

0 条评论

目前还没有评论...

信息

ID
1206
难度
5
分类
搜索 | 搜索与剪枝 点击显示
标签
递交数
1188
已通过
455
通过率
38%
被复制
14
上传者