bzoj 1054 bfs

  就是bfs,对于每个状态存一个hash为当前状态矩阵的二进制表示,然后搜就行了,写成双向bfs会快很多。

  反思:对于C++的数组从0开始还不是特别习惯,经常犯错,对于C++的结构体不熟。

/**************************************************************
    Problem: 1054
    User: BLADEVIL
    Language: C++
    Result: Accepted
    Time:112 ms
    Memory:1940 kb
****************************************************************/
 
//By BLADEVIL
#include <cstdio>
#include <iostream>
#include <queue>
#include <set>
#define LL long long
 
using namespace std;
 
const int go[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
 
struct rec
{
    int map[5][5];
};
 
struct node
{
    rec x;
    int y;
    node(rec xx,int yy):x(xx),y(yy){}
};
 
LL hash(rec x)
{
    LL h=0;
    for (int i=1;i<=4;i++)
        for (int j=1;j<=4;j++)
            h^=(x.map[i][j]<<(4*(i-1)+(j-1)));
    return h;   
}
 
int main()
{
    queue<node>que;
    set<LL>bt;
    rec start,finish;
    for (int i=1;i<=4;i++)
    {
        char c[10];
        scanf("%s",&c);
        for (int j=0;j<4;j++) start.map[i][j+1]=(c[j]=='1')?1:0;
    }
    for (int i=1;i<=4;i++)
    {
        char c[10];
        scanf("%s",&c);
        for (int j=0;j<4;j++) finish.map[i][j+1]=(c[j]=='1')?1:0;
    }
    //printf("%lld %lld
",hash(start),hash(finish));
    if (hash(start)==hash(finish)) 
    {
        printf("0
");
        return 0;
    }
    que.push(node(start,0)); bt.insert(hash(start));
    while (!que.empty())
    {
        node cur=que.front(); que.pop();
        //printf("%lld ",hash(cur.x));
        for (int i=1;i<=4;i++)
            for (int j=1;j<=4;j++) if (cur.x.map[i][j])
                for (int k=0;k<4;k++)
                {
                    int x=i+go[k][0],y=j+go[k][1];
                    //printf("%d %d ",i,j);
                    //printf("%d %d |",x,y);
                    if ((!x)||(x>4)||(!y)||(y>4)) continue;
                    if (cur.x.map[x][y]) continue;
                    rec next=cur.x;
                    next.map[x][y]=next.map[i][j]--;
                    if (bt.count(hash(next))) continue;
                    que.push(node(next,cur.y+1)); bt.insert(hash(next));
                    if (hash(finish)==hash(next))
                    {
                        printf("%d
",cur.y+1);
                        return 0;
                    }
                }
    }
    return 0;
}
 
原文地址:https://www.cnblogs.com/BLADEVIL/p/3557131.html