[BZOJ1054][HAOI2008]移动玩具(bfs+hash)

题目:

我是超链接

题解:

感觉用bitset也可以啊,但是可以发现记录一个状态只需要一个二进制的值,那就hash一下移动吧

代码:

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#define ull unsigned long long
using namespace std;
struct hh{int a[10][10],bs;}be;
int ed,w;bool vis[100000];
const int cc[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
bool check(hh a)
{
    int i,j;w=0;
    for (i=1;i<=4;i++)
        for (j=1;j<=4;j++)
        if (a.a[i][j])
        {
            int lx=(i-1)*4+j;
            w+=(1<<lx-1);
        }  
    return w==ed;
}
void bfs()
{
    queue<hh>q;
    int i,j,k;
    be.bs=0;
    if (check(be)){printf("0");return;}
    q.push(be);
    memset(vis,0,sizeof(vis));
    vis[w]=1;
    while (!q.empty())
    {
        hh now=q.front(); q.pop();
        for (i=1;i<=4;i++)
          for (j=1;j<=4;j++)
            if (now.a[i][j]==1)
            {
                for (k=0;k<4;k++)
                { 
                    hh wh=now;
                    int xx=i+cc[k][0],yy=j+cc[k][1];
                    if (xx<1 || yy<1 || xx>4 || yy>4 || now.a[xx][yy]==1) continue;
                    wh.a[i][j]=0;
                    wh.a[xx][yy]=1;
                    if (check(wh)){printf("%d",now.bs+1);return;}
                    if (!vis[w]) 
                    {
                        wh.bs++;
                        vis[w]=1,q.push(wh);
                    }
                }
            }
    }
}
int main()
{
    int i,j;char st[10];
    for (i=1;i<=4;i++)
    {
        scanf("%s",st+1);
        for (j=1;j<=4;j++)
          be.a[i][j]=st[j]-'0';
    }  
    for (i=1;i<=4;i++)
    {
        scanf("%s",st+1);
        for (j=1;j<=4;j++)
          if (st[j]=='1')
          {
            int lx=(i-1)*4+j;
            ed+=(1<<lx-1);
          }
    }
    bfs();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值