BZOJ1054 [HAOI2008]移动玩具(洛谷P4289)

BFS 状压

BZOJ题目传送门
洛谷题目传送门

最多只可能有 2 16 种情况。但是因为玩具数量是一定的,所以总情况远远不到。状压后直接BFS即可。

据说这道题不判重都能过。。。

代码:

#include<queue>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int t1[4]={1,0,-1,0};
const int t2[4]={0,1,0,-1};
struct node{ int x,p; };
int s,t;
bool f[1<<18];
queue <node> q;
inline int _read(){
    char ch=getchar();
    while (!isdigit(ch)) ch=getchar();
    return ch-48;
}
inline bool pd(int p,int x,int y){ return !(p&(1<<(x-1)*4+y-1)); }
inline int bfs(){
    q.push((node){s,0}),f[s]=true;
    while (!q.empty()){
        node a=q.front(); q.pop();
        if (a.x==t) return a.p;
        for (int i=0;i<16;i++)
            if ((1<<i)&a.x){
                int x=i/4+1,y=i%4+1,p=a.x-(1<<i);
                for (int j=0;j<4;j++){
                    int l=x+t1[j],r=y+t2[j],n=p+(1<<(l-1)*4+r-1);
                    if (l&&r&&l<5&&r<5&&pd(p,l,r)&&!f[n])
                        q.push((node){n,a.p+1}),f[n]=true;
                }
            }
    }
}
int main(){
    for (int i=1;i<5;i++)
        for (int j=1,x;j<5;j++)
            x=_read(),s+=x<<(i-1)*4+j-1;
    for (int i=1;i<5;i++)
        for (int j=1,x;j<5;j++)
            x=_read(),t+=x<<(i-1)*4+j-1;
    return printf("%d\n",bfs()),0;
}

猜你喜欢

转载自blog.csdn.net/a1799342217/article/details/80927039